text stringlengths 49 1.09k | source stringclasses 119
values | id stringlengths 14 15 |
|---|---|---|
</button>
)
}
Enhancements
Experimental useOptimistic
The experimental useOptimistic hook provides a way to implement optimistic updates in your application. Optimistic updates are a technique that enhances user experience by making the app appear more responsive.
When a Server Action is invoked, the UI is updated im... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-9 |
)
const formRef = useRef()
return (
<div>
{optimisticMessages.map((m) => (
<div>
{m.message}
{m.sending ? 'Sending...' : ''}
</div>
))}
<form
action={async (formData) => {
const message = formData.get('message')
formRef.current.... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-10 |
app/form.js 'use client'
import { experimental_useFormStatus as useFormStatus } from 'react-dom'
function Submit() {
const { pending } = useFormStatus()
return (
<input
type="submit"
className={pending ? 'button-pending' : 'button-normal'}
disabled={pending}
>
Submit
</inpu... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-11 |
If a Client Action is passed to a <form>, the form is still interactive, but the action will be placed in a queue until the form has hydrated. The <form> is prioritized with Selective Hydration, so it happens quickly.
app/components/example-client-component.js 'use client'
import { useState } from 'react'
import { ha... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-12 |
Size Limitation
By default, the maximum size of the request body sent to a Server Action is 1MB. This prevents large amounts of data being sent to the server, which consumes a lot of server resource to parse.
However, you can configure this limit using the experimental serverActionsBodySizeLimit option. It can take the... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-13 |
app/actions.js 'use server'
export async function addItem() {
// ...
}
app/components/example-client-component.js 'use client'
import { useTransition } from 'react'
import { addItem } from '../actions'
function ExampleClientComponent({ id }) {
let [isPending, startTransition] = useTransition()
return (
... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-14 |
app/components/example-server-component.js import { ExampleClientComponent } from './components/example-client-component.js'
function ExampleServerComponent({ id }) {
async function updateItem(data) {
'use server'
modifyItem({ id, data })
}
return <ExampleClientComponent updateItem={updateItem} />
}
a... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-15 |
</form>
)
}
On-demand Revalidation
Server Actions can be used to revalidate data on-demand by path (revalidatePath) or by cache tag (revalidateTag).
import { revalidateTag } from 'next/cache'
async function revalidate() {
'use server'
revalidateTag('blog-posts')
}
Validation
The data passed to a Server Action ... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-16 |
return async (formData) => {
'use server'
const isValidData = verifyData(formData)
if (!isValidData) {
throw new Error('Invalid input.')
}
const data = process(formData)
return action(data)
}
}
Using headers
You can read incoming request headers such as cookies and headers within a... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-17 |
'use server';
const cart = await createCart():
cookies().set('cartId', cart.id)
// or
cookies().set({
name: 'cartId',
value: cart.id,
httpOnly: true,
path: '/'
})
}
Glossary
Actions
Actions are an experimental feature in React, allowing you to run async code in response to a user interaction... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-18 |
React also provides built-in solutions for optimistic updates with Actions. It's important to note new patterns are still being developed and new APIs may still be added.
Form Actions
Actions integrated into the web standard <form> API, and enable out-of-the-box progressive enhancement and loading states. Similar to th... | https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions | cc4a940c4965-19 |
Data FetchingThe Next.js App Router allows you to fetch data directly in your React components by marking the function as async and using await for the Promise.
Data fetching is built on top of the fetch() Web API and React Server Components. When using fetch(), requests are automatically deduped by default.
Next.js ex... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-0 |
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main></main>
}
Good to know:
To use an async Server Component with TypeScript, ensure you are using TypeScript 5.1.3 or higher and @types/react 18.2.8 or higher.
Server... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-1 |
Wrapping fetch in use is currently not recommended in Client Components and may trigger multiple re-renders. For now, if you need to fetch data in a Client Component, we recommend using a third-party library such as SWR or React Query.
Good to know: We'll be adding more examples once fetch and use work in Client Compon... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-2 |
See Revalidating Data for more information.
Good to know:
Caching at the fetch level with revalidate or cache: 'force-cache' stores the data across requests in a shared cache. You should avoid using it for user-specific data (i.e. requests that derive data from cookies() or headers())
Dynamic Data Fetching
To fetch fre... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-3 |
return res.json()
}
async function getArtistAlbums(username: string) {
const res = await fetch(`https://api.example.com/artist/${username}/albums`)
return res.json()
}
export default async function Page({
params: { username },
}: {
params: { username: string }
}) {
// Initiate both requests in parallel
... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-4 |
</>
)
}
By starting the fetch prior to calling await in the Server Component, each request can eagerly start to fetch requests at the same time. This sets the components up so you can avoid waterfalls.
We can save time by initiating both requests in parallel, however, the user won't see the rendered result until both... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-5 |
const albumData = getArtistAlbums(username)
// Wait for the artist's promise to resolve first
const artist = await artistData
return (
<>
<h1>{artist.name}</h1>
{/* Send the artist information first,
and wrap albums in a suspense boundary */}
<Suspense fallback={<div>Loading...... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-6 |
))}
</ul>
)
}
Take a look at the preloading pattern for more information on improving components structure.
Sequential Data Fetching
To fetch data sequentially, you can fetch directly inside the component that needs it, or you can await the result of fetch inside the component that needs it:
app/artist/page.tsx /... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-7 |
}: {
params: { username: string }
}) {
// Wait for the artist
const artist = await getArtist(username)
return (
<>
<h1>{artist.name}</h1>
<Suspense fallback={<div>Loading...</div>}>
<Playlists artistID={artist.id} />
</Suspense>
</>
)
}
By fetching data inside the component... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-8 |
In the pages directory, pages using server-rendering would show the browser loading spinner until getServerSideProps had finished, then render the React component for that page. This can be described as "all or nothing" data fetching. Either you had the entire data for your page, or none.
In the app directory, you have... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-9 |
Data Fetching without fetch()
You might not always have the ability to use and configure fetch requests directly if you're using a third-party library such as an ORM or database client.
In cases where you cannot use fetch but still want to control the caching or revalidating behavior of a layout or page, you can rely o... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-10 |
Good to know: Dynamic functions like cookies() and headers() will make the route segment dynamic.
Segment Cache Configuration
As a temporary solution, until the caching behavior of third-party queries can be configured, you can use segment configuration to customize the cache behavior of the entire segment.
app/page.ts... | https://nextjs.org/docs/app/building-your-application/data-fetching/fetching | d0aef57c7f0c-11 |
Revalidating DataNext.js allows you to update specific static routes without needing to rebuild your entire site. Revalidation (also known as Incremental Static Regeneration) allows you to retain the benefits of static while scaling to millions of pages.
There are two types of revalidation in Next.js:
Background: Reval... | https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating | 50796af62b23-0 |
app/page.tsx export const revalidate = 60 // revalidate this page every 60 seconds
In addition to fetch, you can also revalidate data using cache.
How it works
When a request is made to the route that was statically rendered at build time, it will initially show the cached data.
Any requests to the route after the init... | https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating | 50796af62b23-1 |
Good to know: Check if your upstream data provider has caching enabled by default. You might need to disable (e.g. useCdn: false), otherwise a revalidation won't be able to pull fresh data to update the ISR cache. Caching can occur at a CDN (for an endpoint being requested) when it returns the Cache-Control header. ISR... | https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating | 50796af62b23-2 |
Content from your headless CMS is created or updated.
Ecommerce metadata changes (price, description, category, reviews, etc).
Using On-Demand Revalidation
Data can be revalidated on-demand by path (revalidatePath) or by cache tag (revalidateTag).
For example, the following fetch adds the cache tag collection:
app/page... | https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating | 50796af62b23-3 |
export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
Error Handling and Revalidation
If an error is thrown while attempting to revalidate data, the last successfully generated dat... | https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating | 50796af62b23-4 |
Caching DataNext.js has built-in support for caching data, both on a per-request basis (recommended) or for an entire route segment.
Per-request Caching
fetch()
By default, all fetch() requests are cached and deduplicated automatically. This means that if you make the same request twice, the second request will reuse t... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-0 |
const comments = await getComments() // cache HIT
Requests are not cached if:
Dynamic methods (next/headers, export const POST, or similar) are used and the fetch is a POST request (or uses Authorization or cookie headers)
fetchCache is configured to skip cache by default
revalidate: 0 or cache: 'no-store' is configure... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-1 |
const data = res.json()
// ...
}
React cache()
React allows you to cache() and deduplicate requests, memoizing the result of the wrapped function call. The same function called with the same arguments will reuse a cached value instead of re-running the function.
utils/getUser.ts import { cache } from 'react'
export... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-2 |
export default async function Page({
params: { id },
}: {
params: { id: string }
}) {
const user = await getUser(id)
// ...
}
Although the getUser() function is called twice in the example above, only one query will be made to the database. This is because getUser() is wrapped in cache(), so the second request ... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-3 |
POST requests and cache()
POST requests are automatically deduplicated when using fetch – unless they are inside of POST Route Handler or come after reading headers()/cookies(). For example, if you are using GraphQL and POST requests in the above cases, you can use cache to deduplicate requests. The cache arguments mus... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-4 |
export const preload = (id: string) => {
// void evaluates the given expression and returns undefined
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
void getUser(id)
}
export default async function User({ id }: { id: string }) {
const result = await getUser(id)
// ...
}
By... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-5 |
}
Good to know:
The preload() function can have any name. It's a pattern, not an API.
This pattern is completely optional and something you can use to optimize on a case-by-case basis.
This pattern is a further optimization on top of parallel data fetching. Now you don't have to pass promises down as props and can inst... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-6 |
export const getUser = cache(async (id: string) => {
// ...
})
With this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching only happens on the server.
The getUser.ts exports can be used by layouts, pages, or components to give them control over when a user's data is fetched.... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-7 |
Good to know:
If a page, layout, and fetch request inside components all specify a revalidate frequency, the lowest value of the three will be used.
Advanced: You can set fetchCache to 'only-cache' or 'force-cache' to ensure that all fetch requests opt into caching but the revalidation frequency might still be lowered ... | https://nextjs.org/docs/app/building-your-application/data-fetching/caching | 86d8c1721ec5-8 |
CSS Modules
Next.js has built-in support for CSS Modules using the .module.css extension.
CSS Modules locally scope CSS by automatically creating a unique class name. This allows you to use the same class name in different files without worrying about collisions. This behavior makes CSS Modules the ideal way to include... | https://nextjs.org/docs/app/building-your-application/styling/css-modules | 1ae9116e737c-0 |
Regular <link> stylesheets and global CSS files are still supported.
In production, all CSS Module files will be automatically concatenated into many minified and code-split .css files.
These .css files represent hot execution paths in your application, ensuring the minimal amount of CSS is loaded for your application ... | https://nextjs.org/docs/app/building-your-application/styling/css-modules | 1ae9116e737c-1 |
import './global.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
External Stylesheets
Stylesheets published by external packages can be imported anywhere in the app directory, including colocate... | https://nextjs.org/docs/app/building-your-application/styling/css-modules | 1ae9116e737c-2 |
Additional Features
Next.js includes additional features to improve the authoring experience of adding styles:
When running locally with next dev, local stylesheets (either global or CSS modules) will take advantage of Fast Refresh to instantly reflect changes as edits are saved.
When building for production with next ... | https://nextjs.org/docs/app/building-your-application/styling/css-modules | 1ae9116e737c-3 |
Tailwind CSS
Tailwind CSS is a utility-first CSS framework that works exceptionally well with Next.js.
Installing Tailwind
Install the Tailwind CSS packages and run the init command to generate both the tailwind.config.js and postcss.config.js files:
Terminal npm install -D tailwindcss postcss autoprefixer
npx tailwind... | https://nextjs.org/docs/app/building-your-application/styling/tailwind-css | a862eab045a9-0 |
'./components/**/*.{js,ts,jsx,tsx,mdx}',
// Or if using `src` directory:
'./src/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
},
plugins: [],
}
You do not need to modify postcss.config.js.
Importing Styles
Add the Tailwind CSS directives that Tailwind will use to inject its generated styles t... | https://nextjs.org/docs/app/building-your-application/styling/tailwind-css | a862eab045a9-1 |
// These styles apply to every route in the application
import './globals.css'
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
... | https://nextjs.org/docs/app/building-your-application/styling/tailwind-css | a862eab045a9-2 |
Sass
Next.js has built-in support for Sass using both the .scss and .sass extensions. You can use component-level Sass via CSS Modules and the .module.scssor .module.sass extension.
First, install sass:
Terminal npm install --save-dev sass
Good to know:
Sass supports two different syntax, each with their own extension.... | https://nextjs.org/docs/app/building-your-application/styling/sass | b1a4f3c89a06-0 |
module.exports = {
sassOptions: {
includePaths: [path.join(__dirname, 'styles')],
},
}
Sass Variables
Next.js supports Sass variables exported from CSS Module files.
For example, using the exported primaryColor Sass variable:
app/variables.module.scss $primary-color: #64ff00;
:export {
primaryColor: $primar... | https://nextjs.org/docs/app/building-your-application/styling/sass | b1a4f3c89a06-1 |
CSS-in-JS
Warning: CSS-in-JS libraries which require runtime JavaScript are not currently supported in Server Components. Using CSS-in-JS with newer React features like Server Components and Streaming requires library authors to support the latest version of React, including concurrent rendering.
We're working with the... | https://nextjs.org/docs/app/building-your-application/styling/css-in-js | db921053a4f9-0 |
If you want to style Server Components, we recommend using CSS Modules or other solutions that output CSS files, like PostCSS or Tailwind CSS.Configuring CSS-in-JS in app
Configuring CSS-in-JS is a three-step opt-in process that involves:
A style registry to collect all CSS rules in a render.
The new useServerInsertedH... | https://nextjs.org/docs/app/building-your-application/styling/css-in-js | db921053a4f9-1 |
export default function StyledJsxRegistry({
children,
}: {
children: React.ReactNode
}) {
// Only create stylesheet once with lazy initial state
// x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [jsxStyleRegistry] = useState(() => createStyleRegistry())
useServerInsertedHTML... | https://nextjs.org/docs/app/building-your-application/styling/css-in-js | db921053a4f9-2 |
}) {
return (
<html>
<body>
<StyledJsxRegistry>{children}</StyledJsxRegistry>
</body>
</html>
)
}View an example here.Styled Components
Below is an example of how to configure styled-components@v6.0.0-rc.1 or greater:First, use the styled-components API to create a global registry compon... | https://nextjs.org/docs/app/building-your-application/styling/css-in-js | db921053a4f9-3 |
export default function StyledComponentsRegistry({
children,
}: {
children: React.ReactNode
}) {
// Only create stylesheet once with lazy initial state
// x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
use... | https://nextjs.org/docs/app/building-your-application/styling/css-in-js | db921053a4f9-4 |
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>
<StyledComponentsRegistry>{children}</StyledComponentsRegistry>
</body>
</html>
)
}View an example here.
Good to know:
During server rendering, styles will be extracted to a glob... | https://nextjs.org/docs/app/building-your-application/styling/css-in-js | db921053a4f9-5 |
We specifically use a Client Component at the top level of the tree for the style registry because it's more efficient to extract CSS rules this way. It avoids re-generating styles on subsequent server renders, and prevents them from being sent in the Server Component payload. | https://nextjs.org/docs/app/building-your-application/styling/css-in-js | db921053a4f9-6 |
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 | e460f17e23e6-0 |
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 | e460f17e23e6-1 |
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 | e460f17e23e6-2 |
)
}
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 | e460f17e23e6-3 |
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 | e460f17e23e6-4 |
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 | e460f17e23e6-5 |
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 | e460f17e23e6-6 |
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 | e460f17e23e6-7 |
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 | e460f17e23e6-8 |
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 | 31c7b1ee3ff1-0 |
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 | 31c7b1ee3ff1-1 |
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 | 31c7b1ee3ff1-2 |
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 | 31c7b1ee3ff1-3 |
// 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 | 31c7b1ee3ff1-4 |
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 | 31c7b1ee3ff1-5 |
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 | 31c7b1ee3ff1-6 |
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 | 31c7b1ee3ff1-7 |
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 | 31c7b1ee3ff1-8 |
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 | 31c7b1ee3ff1-9 |
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 | 31c7b1ee3ff1-10 |
}
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 | 31c7b1ee3ff1-11 |
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 | 31c7b1ee3ff1-12 |
}
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 | 31c7b1ee3ff1-13 |
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 | 31c7b1ee3ff1-14 |
<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 | 31c7b1ee3ff1-15 |
// 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 | 31c7b1ee3ff1-16 |
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 | 31c7b1ee3ff1-17 |
// ...
}
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 | 31c7b1ee3ff1-18 |
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 | 31c7b1ee3ff1-19 |
// 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 | 31c7b1ee3ff1-20 |
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 | 31c7b1ee3ff1-21 |
// 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 | 31c7b1ee3ff1-22 |
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 | 31c7b1ee3ff1-23 |
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 | 31c7b1ee3ff1-24 |
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 | 31c7b1ee3ff1-25 |
}
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 | 31c7b1ee3ff1-26 |
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 | 31c7b1ee3ff1-27 |
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 | 31c7b1ee3ff1-28 |
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 | 31c7b1ee3ff1-29 |
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 | 31c7b1ee3ff1-30 |
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 | 31c7b1ee3ff1-31 |
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 | 31c7b1ee3ff1-32 |
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 | 31c7b1ee3ff1-33 |
}
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 | 31c7b1ee3ff1-34 |
Script Optimization
Layout Scripts
To load a third-party script for multiple routes, import next/script and include the script directly in your layout component:app/dashboard/layout.tsx import Script from 'next/script'
export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
retur... | https://nextjs.org/docs/app/building-your-application/optimizing/scripts | e828fcbbfa62-0 |
Application Scripts
To load a third-party script for all routes, import next/script and include the script directly in your root layout:app/layout.tsx import Script from 'next/script'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{ch... | https://nextjs.org/docs/app/building-your-application/optimizing/scripts | e828fcbbfa62-1 |
Strategy
Although the default behavior of next/script allows you load third-party scripts in any page or layout, you can fine-tune its loading behavior by using the strategy property:
beforeInteractive: Load the script before any Next.js code and before any page hydration occurs.
afterInteractive: (default) Load the sc... | https://nextjs.org/docs/app/building-your-application/optimizing/scripts | e828fcbbfa62-2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.