id stringlengths 14 15 | text stringlengths 49 1.09k | source stringlengths 46 101 |
|---|---|---|
3a945247eb53-2 | // This fetch will run on the server during `next build`
const res = await fetch('https://api.example.com/...')
const data = await res.json()
return <main>...</main>
}Client Components
If you want to perform data fetching on the client, you can use a Client Component with SWR to deduplicate requests.app/other/p... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
3a945247eb53-3 | if (!data) return 'Loading...'
return data.title
}Since route transitions happen client-side, this behaves like a traditional SPA. For example, the following index route allows you to navigate to different posts on the client:app/page.tsx import Link from 'next/link'
export default function Page() {
return (
... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
3a945247eb53-4 | </ul>
</>
)
}
Image Optimization
Image Optimization through next/image can be used with a static export by defining a custom image loader in next.config.js. For example, you can optimize images with a service like Cloudinary:
next.config.js /** @type {import('next').NextConfig} */
const nextConfig = {
output: '... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
3a945247eb53-5 | src: string
width: number
quality?: number
}) {
const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`]
return `https://res.cloudinary.com/demo/image/upload/${params.join(
','
)}${src}`
}
You can then use next/image in your application, defining relative paths to the image in Cloudina... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
3a945247eb53-6 | }
Route Handlers
Route Handlers will render a static response when running next build. Only the GET HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from dynamic or static data. For example:app/data.json/route.ts import { NextResponse } from 'next/server'
export async functi... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
3a945247eb53-7 | import { useEffect } from 'react';
export default function ClientComponent() {
useEffect(() => {
// You now have access to `window`
console.log(window.innerHeight);
}, [])
return ...;
}
Unsupported Features
After enabling the static export output mode, all routes inside app are opted-into the followin... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
3a945247eb53-8 | headers in next.config.js
Middleware
Incremental Static Regeneration
Deploying
With a static export, Next.js can be deployed and hosted on any web server that can serve HTML/CSS/JS static assets.
When running next build, Next.js generates the static export into the out folder. Using next export is no longer needed. For... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
3a945247eb53-9 | location / {
try_files /out/index.html =404;
}
location /blog/ {
rewrite ^/blog/(.*)$ /out/blog/$1.html break;
}
error_page 404 /out/404.html;
location = /404.html {
internal;
}
}
Version History
VersionChangesv13.4.0App Router (Stable) adds enhanced static export support, including us... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
b2e25b3d03e3-0 | CodemodsCodemods are transformations that run on your codebase programmatically. This allows a large number of changes to be programmatically applied without having to manually go through every file.
Next.js provides Codemod transformations to help upgrade your Next.js codebase when an API is updated or deprecated.
Usa... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-1 | Terminal npx @next/codemod@latest built-in-next-font .
This codemod uninstalls the @next/font package and transforms @next/font imports into the built-in next/font.
For example:
import { Inter } from '@next/font/google'
Transforms into:
import { Inter } from 'next/font/google'
13.0
Rename Next Image Imports
next-imag... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-2 | export default function Home() {
return (
<div>
<Image1 src="/test.jpg" width="200" height="300" />
<Image2 src="/test.png" width="500" height="400" />
</div>
)
}
Transforms into:
pages/index.js // 'next/image' becomes 'next/legacy/image'
import Image1 from 'next/legacy/image'
// 'next/future/im... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-3 | )
}
Migrate to the New Image Component
next-image-experimental
Terminal npx @next/codemod@latest next-image-experimental .
Dangerously migrates from next/legacy/image to the new next/image by adding inline styles and removing unused props.
Removes layout prop and adds style.
Removes objectFit prop and adds style.
Remov... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-4 | About
</Link>
<Link href="/about">
<a onClick={() => console.log('clicked')}>About</a>
</Link>
// transforms into
<Link href="/about" onClick={() => console.log('clicked')}>
About
</Link>
In cases where auto-fixing can't be applied, the legacyBehavior prop is added. This allows your app to keep functioning using ... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-5 | cra-to-next
Terminal npx @next/codemod cra-to-next
Migrates a Create React App project to Next.js; creating a Pages Router and necessary config to match behavior. Client-side only rendering is leveraged initially to prevent breaking compatibility due to window usage during SSR and can be enabled seamlessly to allow the... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-6 | my-component.js import React from 'react'
export default class Home extends React.Component {
render() {
return <div>Hello World</div>
}
}
9
Transform Anonymous Components into Named Components
name-default-component
Terminal npx @next/codemod name-default-component
Versions 9 and above.
Transforms anonymous co... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-7 | withamp-to-config
Terminal npx @next/codemod withamp-to-config
Transforms the withAmp HOC into Next.js 9 page configuration.
For example:
// Before
import { withAmp } from 'next/amp'
function Home() {
return <h1>My AMP Page</h1>
}
export default withAmp(Home)
// After
export default function Home() {
return <... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
b2e25b3d03e3-8 | For example:
From import React from 'react'
export default class extends React.Component {
render() {
const { pathname } = this.props.url
return <div>Current pathname: {pathname}</div>
}
}
To import React from 'react'
import { withRouter } from 'next/router'
export default withRouter(
class extends React.... | https://nextjs.org/docs/app/building-your-application/upgrading/codemods |
f11f02aeb46b-0 | App Router Incremental Adoption GuideThis guide will help you:
Update your Next.js application from version 12 to version 13
Upgrade features that work in both the pages and the app directories
Incrementally migrate your existing application from pages to app
Upgrading
Node.js Version
The minimum Node.js version is now... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-1 | Terminal npm install -D eslint-config-next@latest
Good to know: You may need to restart the ESLint server in VS Code for the ESLint changes to take effect. Open the Command Palette (cmd+shift+p on Mac; ctrl+shift+p on Windows) and search for ESLint: Restart ESLint Server.
Next Steps
After you've updated, see the follow... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-2 | Upgrading to Next.js 13 does not require using the new App Router. You can continue using pages with new features that work in both directories, such as the updated Image component, Link component, Script component, and Font optimization.
<Image/> Component
Next.js 12 introduced new improvements to the Image Component ... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-3 | next-image-experimental codemod: Dangerously adds inline styles and removes unused props. This will change the behavior of existing components to match the new defaults. To use this codemod, you need to run the next-image-to-legacy-image codemod first.
<Link> Component
The <Link> Component no longer requires manually a... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-4 | // Next.js 13: `<Link>` always renders `<a>` under the hood
<Link href="/about">
About
</Link>
To upgrade your links to Next.js 13, you can use the new-link codemod.
<Script> Component
The behavior of next/script has been updated to support both pages and app, but some changes need to be made to ensure a smooth migra... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-5 | Font Optimization
Previously, Next.js helped you optimize fonts by inlining font CSS. Version 13 introduces the new next/font module which gives you the ability to customize your font loading experience while still ensuring great performance and privacy. next/font is supported in both the pages and app directories.
Whi... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-6 | We recommend reducing the combined complexity of these updates by breaking down your migration into smaller steps. The app directory is intentionally designed to work simultaneously with the pages directory to allow for incremental page-by-page migration.
The app directory supports nested routes and layouts. Learn more... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-7 | Data fetching functions like getServerSideProps and getStaticProps have been replaced with a new API inside app. getStaticPaths has been replaced with generateStaticParams.
pages/_app.js and pages/_document.js have been replaced with a single app/layout.js root layout. Learn more.
pages/_error.js has been replaced with... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-8 | app/layout.tsx export default function RootLayout({
// Layouts must accept a children prop.
// This will be populated with nested layouts or pages
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
The app directory must include a root l... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-9 | export const metadata: Metadata = {
title: 'Home',
description: 'Welcome to Next.js',
}
Migrating _document.js and _app.js
If you have an existing _app or _document file, you can copy the contents (e.g. global styles) to the root layout (app/layout.tsx). Styles in app/layout.tsx will not apply to pages/*. You shoul... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-10 | See before and after exampleBeforecomponents/DashboardLayout.js export default function DashboardLayout({ children }) {
return (
<div>
<h2>My Dashboard</h2>
{children}
</div>
)
}pages/dashboard/index.js import DashboardLayout from '../components/DashboardLayout'
export default function Page() ... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-11 | }
Move the contents of DashboardLayout into a new Client Component to retain pages directory behavior.
app/dashboard/DashboardLayout.js 'use client' // this directive should be at top of the file, before any imports.
// This is a Client Component
export default function DashboardLayout({ children }) {
return (
... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-12 | Step 3: Migrating next/head
In the pages directory, the next/head React component is used to manage <head> HTML elements such as title and meta . In the app directory, next/head is replaced with the new built-in SEO support.
Before:
pages/index.tsx import Head from 'next/head'
export default function Page() {
retur... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-13 | }
See all metadata options.
Step 4: Migrating Pages
Pages in the app directory are Server Components by default. This is different from the pages directory where pages are Client Components.
Data fetching has changed in app. getServerSideProps, getStaticProps and getInitialProps have been replaced for a simpler API.
Th... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-14 | Good to know: This is the easiest migration path because it has the most comparable behavior to the pages directory.
Step 1: Create a new Client Component
Create a new separate file inside the app directory (i.e. app/home-page.tsx or similar) that exports a Client Component. To define Client Components, add the 'use cl... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-15 | <div key={post.id}>{post.title}</div>
))}
</div>
)
}
Step 2: Create a new page
Create a new app/page.tsx file inside the app directory. This is a Server Component by default.
Import the home-page.tsx Client Component into the page.
If you were fetching data in pages/index.js, move the data fetching logic di... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-16 | // Fetch data directly in a Server Component
const recentPosts = await getPosts()
// Forward fetched data to your Client Component
return <HomePage recentPosts={recentPosts} />
}
If your previous page used useRouter, you'll need to update to the new routing hooks. Learn more.
Start your development server and vis... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-17 | The useRouter hook imported from next/router is not supported in the app directory but can continue to be used in the pages directory.
The new useRouter does not return the pathname string. Use the separate usePathname hook instead.
The new useRouter does not return the query object. Use the separate useSearchParams ho... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-18 | // ...
}
In addition, the new useRouter hook has the following changes:
isFallback has been removed because fallback has been replaced.
The locale, locales, defaultLocales, domainLocales values have been removed because built-in i18n Next.js features are no longer necessary in the app directory. Learn more about i18n.
... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-19 | View the useRouter() API reference.
Step 6: Migrating Data Fetching Methods
The pages directory uses getServerSideProps and getStaticProps to fetch data for pages. Inside the app directory, these previous data fetching functions are replaced with a simpler API built on top of fetch() and async React Server Components.
... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-20 | // This request should be cached with a lifetime of 10 seconds.
// Similar to `getStaticProps` with the `revalidate` option.
const revalidatedData = await fetch(`https://...`, {
next: { revalidate: 10 },
})
return <div>...</div>
}
Server-side Rendering (getServerSideProps)
In the pages directory, getServe... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-21 | const projects = await res.json()
return { props: { projects } }
}
export default function Dashboard({ projects }) {
return (
<ul>
{projects.map((project) => (
<li key={project.id}>{project.name}</li>
))}
</ul>
)
}
In the app directory, we can colocate our data fetching inside our ... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-22 | // This function can be named anything
async function getProjects() {
const res = await fetch(`https://...`, { cache: 'no-store' })
const projects = await res.json()
return projects
}
export default async function Dashboard() {
const projects = await getProjects()
return (
<ul>
{projects.map((... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-23 | export async function getServerSideProps({ req, query }) {
const authHeader = req.getHeaders()['authorization'];
const theme = req.cookies['theme'];
return { props: { ... }}
}
export default function Page(props) {
return ...
}
The app directory exposes new read-only functions to retrieve request data:
heade... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-24 | return '...'
}
export default async function Page() {
// You can use `cookies()` or `headers()` inside Server Components
// directly or in your data fetching function
const theme = cookies().get('theme')
const data = await getData()
return '...'
}
Static Site Generation (getStaticProps)
In the pages directo... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-25 | return { props: { projects } }
}
export default function Index({ projects }) {
return projects.map((project) => <div>{project.name}</div>)
}
In the app directory, data fetching with fetch() will default to cache: 'force-cache', which will cache the request data until manually invalidated. This is similar to getStat... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-26 | }
Dynamic paths (getStaticPaths)
In the pages directory, the getStaticPaths function is used to define the dynamic paths that should be pre-rendered at build time.
pages/posts/[id].js // `pages` directory
import PostLayout from '@/components/post-layout'
export async function getStaticPaths() {
return {
paths: ... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-27 | return <PostLayout post={post} />
}
In the app directory, getStaticPaths is replaced with generateStaticParams.
generateStaticParams behaves similarly to getStaticPaths, but has a simplified API for returning route parameters and can be used inside layouts. The return shape of generateStaticParams is an array of segmen... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-28 | return post
}
export default async function Post({ params }) {
const post = await getPost(params)
return <PostLayout post={post} />
}
Using the name generateStaticParams is more appropriate than getStaticPaths for the new model in the app directory. The get prefix is replaced with a more descriptive generate, w... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-29 | pages/posts/[id].js // `pages` directory
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking'
};
}
export async function getStaticProps({ params }) {
...
}
export default function Post({ post }) {
return ...
}
In the app directory the config.dynamicParams property cont... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-30 | app/posts/[id]/page.js // `app` directory
export const dynamicParams = true;
export async function generateStaticParams() {
return [...]
}
async function getPost(params) {
...
}
export default async function Post({ params }) {
const post = await getPost(params);
return ...
}
With dynamicParams set to ... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-31 | pages/index.js // `pages` directory
export async function getStaticProps() {
const res = await fetch(`https://.../posts`)
const posts = await res.json()
return {
props: { posts },
revalidate: 60,
}
}
export default function Index({ posts }) {
return (
<Layout>
<PostList posts={posts} /... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-32 | const data = await res.json()
return data.posts
}
export default async function PostList() {
const posts = await getPosts()
return posts.map((post) => <div>{post.name}</div>)
}
API Routes
API Routes continue to work in the pages/api directory without any changes. However, they have been replaced by Route Ha... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-33 | Step 7: Styling
In the pages directory, global stylesheets are restricted to only pages/_app.js. With the app directory, this restriction has been lifted. Global styles can be added to any layout, page, or component.
CSS Modules
Tailwind CSS
Global Styles
CSS-in-JS
External Stylesheets
Sass
Tailwind CSS
If you're using... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
f11f02aeb46b-34 | }
You'll also need to import your global styles in your app/layout.js file:
app/layout.js import '../styles/globals.css'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
Learn more about styling with Tailwind CSS
Codemods
Next.js provid... | https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration |
04cf7f2db2da-0 | create-next-app
The easiest way to get started with Next.js is by using create-next-app. This CLI tool enables you to quickly start building a new Next.js application, with everything set up for you.
You can create a new app using the default Next.js template, or by using one of the official Next.js examples.
Interacti... | https://nextjs.org/docs/app/api-reference/create-next-app |
04cf7f2db2da-1 | Would you like to use App Router? (recommended) No / Yes
Would you like to customize the default import alias? No / Yes
Once you've answered the prompts, a new project will be created with the correct configuration depending on your answers.
Non-interactive
You can also pass command line arguments to set up a new pro... | https://nextjs.org/docs/app/api-reference/create-next-app |
04cf7f2db2da-2 | --tailwind
Initialize with Tailwind CSS config. (default)
--eslint
Initialize with ESLint config.
--app
Initialize as an App Router project.
--src-dir
Initialize inside a `src/` directory.
--import-alias <alias-to-configure>
Specify import alias to use (default "@/*").
... | https://nextjs.org/docs/app/api-reference/create-next-app |
04cf7f2db2da-3 | -e, --example [name]|[github-url]
An example to bootstrap the app with. You can use an example name
from the official Next.js repo or a public GitHub URL. The URL can use
any branch and/or subdirectory
--example-path <path-to-example>
In a rare case, your GitHub URL might contain a branch name w... | https://nextjs.org/docs/app/api-reference/create-next-app |
04cf7f2db2da-4 | -h, --help output usage information
Why use Create Next App?
create-next-app allows you to create a new Next.js app within seconds. It is officially maintained by the creators of Next.js, and includes a number of benefits:
Interactive Experience: Running npx create-next-app@latest (with no arg... | https://nextjs.org/docs/app/api-reference/create-next-app |
04cf7f2db2da-5 | Tested: The package is part of the Next.js monorepo and tested using the same integration test suite as Next.js itself, ensuring it works as expected with every release. | https://nextjs.org/docs/app/api-reference/create-next-app |
176a5d9303fb-0 | Edge Runtime
The Next.js Edge Runtime is based on standard Web APIs, it supports the following APIs:
Network APIs
APIDescriptionBlobRepresents a blobfetchFetches a resourceFetchEventRepresents a fetch eventFileRepresents a fileFormDataRepresents form dataHeadersRepresents HTTP headersRequestRepresents an HTTP requestRe... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-1 | Stream APIs
APIDescriptionReadableStreamRepresents a readable streamReadableStreamBYOBReaderRepresents a reader of a ReadableStreamReadableStreamDefaultReaderRepresents a reader of a ReadableStreamTransformStreamRepresents a transform streamWritableStreamRepresents a writable streamWritableStreamDefaultWriterRepresents... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-2 | APIDescriptionAbortControllerAllows you to abort one or more DOM requests as and when desiredArrayRepresents an array of valuesArrayBufferRepresents a generic, fixed-length raw binary data bufferAtomicsProvides atomic operations as static methodsBigIntRepresents a whole number with arbitrary precisionBigInt64ArrayRepre... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-3 | Identifier (URI) previously created by encodeURI or by a similar routinedecodeURIComponentDecodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routineDOMExceptionRepresents an error that occurs in the DOMencodeURIEncodes a Uniform Resource Identifier (URI) by re... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-4 | typed array of 64-bit floating point numbersFunctionRepresents a functionInfinityRepresents the mathematical Infinity valueInt8ArrayRepresents a typed array of 8-bit signed integersInt16ArrayRepresents a typed array of 16-bit signed integersInt32ArrayRepresents a typed array of 32-bit signed integersIntlProvides access... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-5 | the eventual completion (or failure) of an asynchronous operation, and its resulting valueProxyRepresents an object that is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc)queueMicrotaskQueues a microtask to be executedRangeErrorRepresen... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-6 | a deep copy of a valueSymbolRepresents a unique and immutable data type that is used as the key of an object propertySyntaxErrorRepresents an error when trying to interpret syntactically invalid codeTypeErrorRepresents an error when a value is not of the expected typeUint8ArrayRepresents a typed array of 8-bit unsigned... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-7 | Next.js Specific Polyfills
AsyncLocalStorage
Environment Variables
You can use process.env to access Environment Variables for both next dev and next build.
Unsupported APIs
The Edge Runtime has some restrictions including:
Native Node.js APIs are not supported. For example, you can't read or write to the filesystem.
n... | https://nextjs.org/docs/app/api-reference/edge |
176a5d9303fb-8 | In rare cases, your code could contain (or import) some dynamic code evaluation statements which can not be reached at runtime and which can not be removed by treeshaking.
You can relax the check to allow specific files with your Middleware or Edge API Route exported configuration:
export const config = {
runtime: '... | https://nextjs.org/docs/app/api-reference/edge |
10a35df783d3-0 | Next.js CLI
The Next.js CLI allows you to start, build, and export your application.
To get a list of the available CLI commands, run the following command inside your project directory:
Terminal npx next -h
(npx comes with npm 5.2+ and higher)
The output should look like this:
Terminal Usage
$ next <command>
Avail... | https://nextjs.org/docs/app/api-reference/next-cli |
10a35df783d3-1 | NODE_OPTIONS='-r esm' next
NODE_OPTIONS='--inspect' next
Good to know: Running next without a command is the same as running next dev
Build
next build creates an optimized production build of your application. The output displays information about each route.
Size – The number of assets downloaded when navigating to th... | https://nextjs.org/docs/app/api-reference/next-cli |
10a35df783d3-2 | After that, you can use the profiler in the same way as you would in development.
You can enable more verbose build output with the --debug flag in next build. This requires Next.js 9.5.3:
Terminal next build --debug
With this flag enabled additional build output like rewrites, redirects, and headers will be shown.
Dev... | https://nextjs.org/docs/app/api-reference/next-cli |
10a35df783d3-3 | You can also set the hostname to be different from the default of 0.0.0.0, this can be useful for making the application available for other devices on the network. The default hostname can be changed with -H, like so:
Terminal npx next dev -H 192.168.1.2
Production
next start starts the application in production mode.... | https://nextjs.org/docs/app/api-reference/next-cli |
10a35df783d3-4 | Keep Alive Timeout
When deploying Next.js behind a downstream proxy (e.g. a load-balancer like AWS ELB/ALB) it's important to configure Next's underlying HTTP server with keep-alive timeouts that are larger than the downstream proxy's timeouts. Otherwise, once a keep-alive timeout is reached for a given TCP connection,... | https://nextjs.org/docs/app/api-reference/next-cli |
10a35df783d3-5 | your application.
If you have other directories that you would like to lint, you can specify them using the --dir
flag:
Terminal next lint --dir utils
Telemetry
Next.js collects completely anonymous telemetry data about general usage.
Participation in this anonymous program is optional, and you may opt-out if you'd not... | https://nextjs.org/docs/app/api-reference/next-cli |
10a35df783d3-6 | Terminal
Operating System:
Platform: linux
Arch: x64
Version: #22-Ubuntu SMP Fri Nov 5 13:21:36 UTC 2021
Binaries:
Node: 16.13.0
npm: 8.1.0
Yarn: 1.22.17
pnpm: 6.24.2
Relevant packages:
next: 12.0.8
react: 17.0.2
react-dom: 17.0.2
This informat... | https://nextjs.org/docs/app/api-reference/next-cli |
b153dcbac54c-0 | Font Module
This API reference will help you understand how to use next/font/google and next/font/local. For features and usage, please see the Optimizing Fonts page.
Font Function Arguments
For usage, review Google Fonts and Local Fonts.
Keyfont/googlefont/localTypeRequiredsrcString or Array of ObjectsYesweightString ... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-1 | src:[{path: './inter/Inter-Thin.ttf', weight: '100',},{path: './inter/Inter-Regular.ttf',weight: '400',},{path: './inter/Inter-Bold-Italic.ttf', weight: '700',style: 'italic',},]
if the font loader function is called in app/page.tsx using src:'../styles/fonts/my-font.ttf', then my-font.ttf is placed in styles/fonts at ... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-2 | Required if the font being used is not variable
Examples:
weight: '400': A string for a single weight value - for the font Inter, the possible values are '100', '200', '300', '400', '500', '600', '700', '800', '900' or 'variable' where 'variable' is the default)
weight: '100 900': A string for the range between 100 and... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-3 | style: 'italic': A string - it can be normal or italic for next/font/google
style: 'oblique': A string - it can take any value for next/font/local but is expected to come from standard font styles
style: ['italic','normal']: An array of 2 values for next/font/google - the values are from normal and italic
subsets
The f... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-4 | You can find a list of all subsets on the Google Fonts page for your font.
axes
Some variable fonts have extra axes that can be included. By default, only the font weight is included to keep the file size down. The possible values of axes depend on the specific font.
Used in next/font/google
Optional
Examples:
axes: ['... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-5 | Optional
Examples:
display: 'optional': A string assigned to the optional value
preload
A boolean value that specifies whether the font should be preloaded or not. The default is true.
Used in next/font/google and next/font/local
Optional
Examples:
preload: false
fallback
The fallback font to use if the font cannot be ... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-6 | For next/font/local: A string or boolean false value that sets whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The possible values are 'Arial', 'Times New Roman' or false. The default is 'Arial'.
Used in next/font/google and next/font/local
Optional
Examples:
adjustFontFallback: fal... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-7 | declarations: [{ prop: 'ascent-override', value: '90%' }]
Applying Styles
You can apply the font styles in three ways:
className
style
CSS Variables
className
Returns a read-only CSS className for the loaded font to be passed to an HTML element.
<p className={inter.className}>Hello, Next.js!</p>
style
Returns a read-o... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-8 | app/page.tsx import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'
const inter = Inter({
variable: '--font-inter',
})
To use the font, set the className of the parent container of the text you would like to style to the font loader's variable value and the className of the tex... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-9 | font-weight: 200;
font-style: italic;
}
In the example above, the text Hello World is styled using the Inter font and the generated font fallback with font-weight: 200 and font-style: italic.
Using a font definitions file
Every time you call the localFont or Google font function, that font will be hosted as one insta... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-10 | // define your variable fonts
const inter = Inter()
const lora = Lora()
// define 2 weights of a non-variable font
const sourceCodePro400 = Source_Sans_Pro({ weight: '400' })
const sourceCodePro700 = Source_Sans_Pro({ weight: '700' })
// define a custom local font where GreatVibes-Regular.ttf is stored in the styles fo... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-11 | export default function Page() {
return (
<div>
<p className={inter.className}>Hello world using Inter font</p>
<p style={lora.style}>Hello world using Lora font</p>
<p className={sourceCodePro700.className}>
Hello world using Source_Sans_Pro font with weight 700
</p>
<p clas... | https://nextjs.org/docs/app/api-reference/components/font |
b153dcbac54c-12 | }
}
}
You can now import any font definition as follows:
app/about/page.tsx import { greatVibes, sourceCodePro400 } from '@/fonts'
Version Changes
VersionChangesv13.2.0@next/font renamed to next/font. Installation no longer required.v13.0.0@next/font was added. | https://nextjs.org/docs/app/api-reference/components/font |
0cbd170b2a92-0 | <Image>
Examples
Image Component
This API reference will help you understand how to use props and configuration options available for the Image Component. For features and usage, please see the Image Component page.
app/page.js import Image from 'next/image'
export default function Page() {
return (
<Image
... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-1 | }
Props
Here's a summary of the props available for the Image Component:
PropExampleTypeRequiredsrcsrc="/profile.png"StringYeswidthwidth={500}Integer (px)Yesheightheight={500}Integer (px)Yesaltalt="Picture of the author"StringYesloaderloader={imageLoader}Function-fillfill={true}Boolean-sizessizes="(max-width: 768px) 10... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-2 | The Image Component requires the following properties: src, width, height, and alt.
app/page.js import Image from 'next/image'
export default function Page() {
return (
<div>
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-3 | Required, except for statically imported images or images with the fill property.
height
The height property represents the rendered height in pixels, so it will affect how large the image appears.
Required, except for statically imported images or images with the fill property.
alt
The alt property is used to describe... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-4 | Learn more
Optional Props
The <Image /> component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the Advanced Props section.
loader
A custom function used to res... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-5 | alt="Picture of the author"
width={500}
height={500}
/>
)
}
Good to know: Using props like loader, which accept a function, require using Client Components to serialize the provided function.
Alternatively, you can use the loaderFile configuration in next.config.js to configure every instance of next/... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-6 | By default, the img element will automatically be assigned the position: "absolute" style.
The default image fit behavior will stretch the image to fit the container. You may prefer to set object-fit: "contain" for an image which is letterboxed to fit the container and preserve aspect ratio.
Alternatively, object-fit: ... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-7 | The sizes property serves two important purposes related to image performance:
First, the value of sizes is used by the browser to determine which size of the image to download, from next/image's automatically-generated source set. When the browser chooses, it does not yet know the size of the image on the page, so it ... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-8 | Second, the sizes property configures how next/image automatically generates an image source set. If no sizes value is present, a small source set is generated, suitable for a fixed-size image. If sizes is defined, a large source set is generated, suitable for a responsive image. If the sizes property includes sizes su... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-9 | <Image
fill
src="/example.png"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
)
}
This example sizes could have a dramatic effect on performance metrics. Without the 33vw sizes, the image selected from the server would be 3 times as wide as it needs to be.... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-10 | priority
priority={false} // {false} | {true}
When true, the image will be considered high priority and
preload. Lazy loading is automatically disabled for images using priority.
You should use the priority property on any image detected as the Largest Contentful Paint (LCP) element. It may be appropriate to have mult... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-11 | For dynamic images, you must provide the blurDataURL property. Solutions such as Plaiceholder can help with base64 generation.
When empty, there will be no placeholder while the image is loading, only empty space.
Try it out:
Demo the blur placeholder
Demo the shimmer effect with blurDataURL prop
Demo the color effect ... | https://nextjs.org/docs/app/api-reference/components/image |
0cbd170b2a92-12 | return <Image src="..." style={imageStyle} />
}
Remember that the required width and height props can interact with your styling. If you use styling to modify an image's width, you should also style its height to auto to preserve its intrinsic aspect ratio, or your image will be distorted.
onLoadingComplete
'use clien... | https://nextjs.org/docs/app/api-reference/components/image |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.