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 immediately to reflect the expected outcome, instead of waiting for the Server Action's response. app/thread.js 'use client' import { experimental_useOptimistic as useOptimistic, useRef } from 'react' import { send } from './actions.js' export function Thread({ messages }) { const [optimisticMessages, addOptimisticMessage] = useOptimistic( messages, (state, newMessage) => [...state, { message: newMessage, sending: true }] ) const formRef = useRef() return (
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.reset() addOptimisticMessage(message) await send(message) }} ref={formRef} > <input type="text" name="message" /> </form> </div> ) } Experimental useFormStatus The experimental useFormStatus hook can be used within Form Actions, and provides the pending property. app/form.js 'use client'
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 </input> ) } Progressive Enhancement Progressive Enhancement allows a <form> to function properly without JavaScript, or with JavaScript disabled. This allows users to interact with the form and submit data even if the JavaScript for the form hasn't been loaded yet or if it fails to load. Both Server Form Actions and Client Form Actions support Progressive Enhancement, using one of two strategies: If a Server Action is passed directly to a <form>, the form is interactive even if JavaScript is disabled.
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 { handleSubmit } from './actions.js' export default function ExampleClientComponent({ myAction }) { const [input, setInput] = useState() return ( <form action={handleSubmit} onChange={(e) => setInput(e.target.value)}> {/* ... */} </form> ) } In both cases, the form is interactive before hydration occurs. Although Server Actions have the additional benefit of not relying on client JavaScript, you can still compose additional behavior with Client Actions where desired without sacrificing interactivity. Size Limitation
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 number of bytes or any string format supported by bytes, for example 1000, '500kb' or '3mb'. next.config.js module.exports = { experimental: { serverActions: true, serverActionsBodySizeLimit: '2mb', }, } Examples Usage with Client Components Import Server Actions cannot be defined within Client Components, but they can be imported. To use Server Actions in Client Components, you can import the action from a file containing a top-level "use server" directive. app/actions.js 'use server' export async function addItem() {
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 ( <button onClick={() => startTransition(() => addItem(id))}> Add To Cart </button> ) } Props Although importing Server Actions is recommended, in some cases you might want to pass down a Server Action to a Client Component as a prop. For example, you might want to use a dynamically generated value within the action. In that case, passing a Server Action down as a prop might be a viable solution.
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} /> } app/components/example-client-component.js 'use client' function ExampleClientComponent({ updateItem }) { async function action(formData) { await updateItem(formData) } return ( <form action={action}> <input type="text" name="name" /> <button type="submit">Update Item</button> </form> ) } On-demand Revalidation
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 can be validated or sanitized before invoking the action. For example, you can create a wrapper function that receives the action as its argument, and returns a function that invokes the action if it's valid. app/actions.js 'use server' import { withValidate } from 'lib/form-validation' export const action = withValidate((data) => { // ... }) lib/form-validation.js export function withValidate(action) { return async (formData) => { 'use server'
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 Server Action. import { cookies } from 'next/headers' async function addItem(data) { 'use server' const cartId = cookies().get('cartId')?.value await saveToDb({ cartId, data }) } Additionally, you can modify cookies within a Server Action. import { cookies } from 'next/headers'; async function create(data) { 'use server'; const cart = await createCart():
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. Actions are not Next.js or React Server Components specific, however, they are not yet available in the stable version of React. When using Actions through Next.js, you are opting into using the React experimental channel. Actions are defined through the action prop on an element. Typically when building HTML forms, you pass a URL to the action prop. With Actions, React now allows you to pass a function directly.
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 the HTML primitive formaction. Server Functions Functions that run on the server, but can be called on the client. Server Actions Server Functions called as an action. Server Actions can be progressively enhanced by passing them to a form element's action prop. The form is interactive before any client-side JavaScript has loaded. This means React hydration is not required for the form to submit. Server Mutations Server Actions that mutates your data and calls redirect, revalidatePath, or revalidateTag.
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 extends the fetch options object to allow each request to set its own caching and revalidating. async and await in Server Components You can use async and await to fetch data in Server Components. app/page.tsx async function getData() { const res = await fetch('https://api.example.com/...') // The return value is *not* serialized // You can return Date, Map, Set, etc. // Recommendation: handle errors if (!res.ok) { // This will activate the closest `error.js` Error Boundary throw new Error('Failed to fetch data')
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 Component Functions Next.js provides helpful server functions you may need when fetching data in Server Components: cookies() headers() use in Client Components use is a new React function that accepts a promise conceptually similar to await. use handles the promise returned by a function in a way that is compatible with components, hooks, and Suspense. Learn more about use in the React RFC.
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 Components. Static Data Fetching By default, fetch will automatically fetch and cache data indefinitely. fetch('https://...') // cache: 'force-cache' is the default Revalidating Data To revalidate cached data at a timed interval, you can use the next.revalidate option in fetch() to set the cache lifetime of a resource (in seconds). fetch('https://...', { next: { revalidate: 10 } }) See Revalidating Data for more information. Good to know:
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 fresh data on every fetch request, use the cache: 'no-store' option. fetch('https://...', { cache: 'no-store' }) Data Fetching Patterns Parallel Data Fetching To minimize client-server waterfalls, we recommend this pattern to fetch data in parallel: app/artist/[username]/page.tsx import Albums from './albums' async function getArtist(username: string) { const res = await fetch(`https://api.example.com/artist/${username}`) return res.json() }
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 const artistData = getArtist(username) const albumsData = getArtistAlbums(username) // Wait for the promises to resolve const [artist, albums] = await Promise.all([artistData, albumsData]) return ( <> <h1>{artist.name}</h1> <Albums list={albums}></Albums> </> ) }
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 promises are resolved. To improve the user experience, you can add a suspense boundary to break up the rendering work and show part of the result as soon as possible: artist/[username]/page.tsx import { getArtist, getArtistAlbums, type Album } from './api' export default async function Page({ params: { username }, }: { params: { username: string } }) { // Initiate both requests in parallel const artistData = getArtist(username) const albumData = getArtistAlbums(username)
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...</div>}> <Albums promise={albumData} /> </Suspense> </> ) } // Albums Component async function Albums({ promise }: { promise: Promise<Album[]> }) { // Wait for the albums promise to resolve const albums = await promise return ( <ul> {albums.map((album) => ( <li key={album.id}>{album.name}</li> ))} </ul> )
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 // ... async function Playlists({ artistID }: { artistID: string }) { // Wait for the playlists const playlists = await getArtistPlaylists(artistID) return ( <ul> {playlists.map((playlist) => ( <li key={playlist.id}>{playlist.name}</li> ))} </ul> ) } export default async function Page({ params: { username }, }: { params: { username: string } }) {
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, each fetch request and nested segment in the route cannot start fetching data and rendering until the previous request or segment has completed. Blocking Rendering in a Route By fetching data in a layout, rendering for all route segments beneath it can only start once the data has finished loading.
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 additional options to explore: First, you can use loading.js to show an instant loading state from the server while streaming in the result from your data fetching function. Second, you can move data fetching lower in the component tree to only block rendering for the parts of the page that need it. For example, moving data fetching to a specific component rather than fetching it at the root layout. Whenever possible, it's best to fetch data in the segment that uses it. This also allows you to show a loading state for only the part of the page that is loading, and not the entire page. Data Fetching without fetch()
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 on the default caching behavior of the segment or use the segment cache configuration. Default Caching Behavior Any data fetching libraries that do not use fetch directly will not affect caching of a route, and will be static or dynamic depending on the route segment. If the segment is static (default), the output of the request will be cached and revalidated (if configured) alongside the rest of the segment. If the segment is dynamic, the output of the request will not be cached and will be re-fetched on every request when the segment is rendered. Good to know: Dynamic functions like cookies() and headers() will make the route segment dynamic.
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.tsx import prisma from './lib/prisma' export const revalidate = 3600 // revalidate every hour async function getPosts() { const posts = await prisma.post.findMany() return posts } export default async function Page() { const posts = await getPosts() // ... }
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: Revalidates the data at a specific time interval. On-demand: Revalidates the data based on an event such as an update. Background Revalidation To revalidate cached data at a specific interval, you can use the next.revalidate option in fetch() to set the cache lifetime of a resource (in seconds). fetch('https://...', { next: { revalidate: 60 } }) If you want to revalidate data that does not use fetch (i.e. using an external package or query builder), you can use the route segment config.
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 initial request and before 60 seconds are also cached and instantaneous. After the 60-second window, the next request will still show the cached (stale) data. Next.js will trigger a regeneration of the data in the background. Once the route generates successfully, Next.js will invalidate the cache and show the updated route. If the background regeneration fails, the old data would still be unaltered. When a request is made to a route segment that hasn’t been generated, Next.js will dynamically render the route on the first request. Future requests will serve the static route segments from the cache.
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 on Vercel persists the cache globally and handles rollbacks. On-demand Revalidation If you set a revalidate time of 60, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache is if someone visits the page after the minute has passed. The Next.js App Router supports revalidating content on-demand based on a route or cache tag. This allows you to manually purge the Next.js cache for specific fetches, making it easier to update your site when: Content from your headless CMS is created or updated.
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.tsx export default async function Page() { const res = await fetch('https://...', { next: { tags: ['collection'] } }) const data = await res.json() // ... } This cached data can then be revalidated on-demand by calling revalidateTag in a Route Handler. app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server' import { revalidateTag } from 'next/cache' export async function GET(request: NextRequest) {
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 data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data.
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 the result from the first request. app/page.tsx async function getComments() { const res = await fetch('https://...') // The result is cached return res.json() } // This function is called twice, but the result is only fetched once const comments = await getComments() // cache MISS // The second call could be anywhere in your application const comments = await getComments() // cache HIT Requests are not cached if:
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 configured on individual fetch Requests made using fetch can specify a revalidate option to control the revalidation frequency of the request. app/page.tsx export default async function Page() { // revalidate this data every 10 seconds at most const res = await fetch('https://...', { next: { revalidate: 10 } }) const data = res.json() // ... } React cache()
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 const getUser = cache(async (id: string) => { const user = await db.user.findUnique({ id }) return user }) app/user/[id]/layout.tsx import { getUser } from '@utils/getUser' export default async function UserLayout({ params: { id }, }: { params: { id: string } }) { const user = await getUser(id) // ... } app/user/[id]/page.tsx import { getUser } from '@utils/getUser'
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 can reuse the result from the first request. Good to know: fetch() caches requests automatically, so you don't need to wrap functions that use fetch() with cache(). See automatic request deduping for more information. In this new model, we recommend fetching data directly in the component that needs it, even if you're requesting the same data in multiple components, rather than passing the data between components as props. We recommend using the server-only package to make sure server data fetching functions are never used on the client. POST requests and cache()
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 must be flat and only include primitives. Deep objects won't match for deduplication. utils/getUser.ts import { cache } from 'react' export const getUser = cache(async (id: string) => { const res = await fetch('...', { method: 'POST', body: '...' }) // ... }) Preload pattern with cache() As a pattern, we suggest optionally exposing a preload() export in utilities or components that do data fetching. components/User.tsx import { getUser } from '@utils/getUser' export const preload = (id: string) => {
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 calling preload, you can eagerly start fetching data you're likely going to need. app/user/[id]/page.tsx import User, { preload } from '@components/User' export default async function Page({ params: { id }, }: { params: { id: string } }) { preload(id) // starting loading the user data now const condition = await fetchCondition() return condition ? <User id={id} /> : null } Good to know:
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 instead rely on the preload pattern. Combining cache, preload, and server-only You can combine the cache function, the preload pattern, and the server-only package to create a data fetching utility that can be used throughout your app. utils/getUser.ts import { cache } from 'react' import 'server-only' export const preload = (id: string) => { void getUser(id) } export const getUser = cache(async (id: string) => { // ... })
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. Segment-level Caching Good to know: We recommend using per-request caching for improved granularity and control over caching. Segment-level caching allows you to cache and revalidate data used in route segments. This mechanism allows different segments of a path to control the cache lifetime of the entire route. Each page.tsx and layout.tsx in the route hierarchy can export a revalidate value that sets the revalidation time for the route. app/page.tsx export const revalidate = 60 // revalidate this segment every 60 seconds Good to know:
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 by individual fetch requests. See fetchCache for more information.
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 component-level CSS. Example CSS Modules can be imported into any file inside the app directory:app/dashboard/layout.tsx import styles from './styles.module.css' export default function DashboardLayout({ children, }: { children: React.ReactNode }) { return <section className={styles.dashboard}>{children}</section> }app/dashboard/styles.module.css .dashboard { padding: 24px; } CSS Modules are an optional feature and are only enabled for files with the .module.css extension. Regular <link> stylesheets and global CSS files are still supported.
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 to paint. Global Styles Global styles can be imported into any layout, page, or component inside the app directory. Good to know: This is different from the pages directory, where you can only import global styles inside the _app.js file. For example, consider a stylesheet named app/global.css: body { padding: 20px 20px 60px; max-width: 680px; margin: 0 auto; }Inside the root layout (app/layout.js), import the global.css stylesheet to apply the styles to every route in your application:app/layout.tsx // These styles apply to every route in the 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 colocated components:app/layout.tsx import 'bootstrap/dist/css/bootstrap.css' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body className="container">{children}</body> </html> ) } Good to know: External stylesheets must be directly imported from an npm package or downloaded and colocated with your codebase. You cannot use <link rel="stylesheet" />. Additional Features
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 build, CSS files will be bundled into fewer minified .css files to reduce the number of network requests needed to retrieve styles. If you disable JavaScript, styles will still be loaded in the production build (next start). However, JavaScript is still required for next dev to enable Fast Refresh.
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 tailwindcss init -p Configuring Tailwind Inside tailwind.config.js, add paths to the files that will use Tailwind CSS class names: tailwind.config.js /** @type {import('tailwindcss').Config} */ module.exports = { content: [ './app/**/*.{js,ts,jsx,tsx,mdx}', // Note the addition of the `app` directory. './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}',
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 to a Global Stylesheet in your application, for example:app/globals.css @tailwind base; @tailwind components; @tailwind utilities;Inside the root layout (app/layout.tsx), import the globals.css stylesheet to apply the styles to every route in your application.app/layout.tsx import type { Metadata } from 'next' // These styles apply to every route in the application import './globals.css'
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"> <body>{children}</body> </html> ) }Using Classes After installing Tailwind CSS and adding the global styles, you can use Tailwind's utility classes in your application.app/page.tsx export default function Page() { return <h1 className="text-3xl font-bold underline">Hello, Next.js!</h1> } Usage with Turbopack As of Next.js 13.1, Tailwind CSS and PostCSS are supported with Turbopack.
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. The .scss extension requires you use the SCSS syntax, while the .sass extension requires you use the Indented Syntax ("Sass"). If you're not sure which to choose, start with the .scss extension which is a superset of CSS, and doesn't require you learn the Indented Syntax ("Sass"). Customizing Sass Options If you want to configure the Sass compiler, use sassOptions in next.config.js. next.config.js const path = require('path') module.exports = { sassOptions: {
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: $primary-color; } app/page.js // maps to root `/` URL import variables from './variables.module.scss' export default function Page() { return <h1 style={{ color: variables.primaryColor }}>Hello, Next.js!</h1> }
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 React team on upstream APIs to handle CSS and JavaScript assets with support for React Server Components and streaming architecture. The following libraries are supported in Client Components in the app directory (alphabetical): kuma-ui @mui/material pandacss styled-jsx styled-components style9 tamagui tss-react vanilla-extract The following are currently working on support: emotion Good to know: We're testing out different CSS-in-JS libraries and we'll be adding more examples for libraries that support React 18 features and/or the app directory.
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 useServerInsertedHTML hook to inject rules before any content that might use them. A Client Component that wraps your app with the style registry during initial server-side rendering. styled-jsx Using styled-jsx in Client Components requires using v5.1.0. First, create a new registry:app/registry.tsx 'use client' import React, { useState } from 'react' import { useServerInsertedHTML } from 'next/navigation' import { StyleRegistry, createStyleRegistry } from 'styled-jsx' export default function StyledJsxRegistry({ children,
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(() => { const styles = jsxStyleRegistry.styles() jsxStyleRegistry.flush() return <>{styles}</> }) return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry> }Then, wrap your root layout with the registry:app/layout.tsx import StyledJsxRegistry from './registry' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html> <body>
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 [email protected] or greater:First, use the styled-components API to create a global registry component to collect all CSS style rules generated during a render, and a function to return those rules. Then use the useServerInsertedHTML hook to inject the styles collected in the registry into the <head> HTML tag in the root layout.lib/registry.tsx 'use client' import React, { useState } from 'react' import { useServerInsertedHTML } from 'next/navigation' import { ServerStyleSheet, StyleSheetManager } from 'styled-components' export default function StyledComponentsRegistry({
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()) useServerInsertedHTML(() => { const styles = styledComponentsStyleSheet.getStyleElement() styledComponentsStyleSheet.instance.clearTag() return <>{styles}</> }) if (typeof window !== 'undefined') return <>{children}</> return ( <StyleSheetManager sheet={styledComponentsStyleSheet.instance}> {children} </StyleSheetManager> ) }Wrap the children of the root layout with the style registry component:app/layout.tsx import StyledComponentsRegistry from './lib/registry'
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 global registry and flushed to the <head> of your HTML. This ensures the style rules are placed before any content that might use them. In the future, we may use an upcoming React feature to determine where to inject the styles. During streaming, styles from each chunk will be collected and appended to existing styles. After client-side hydration is complete, styled-components will take over as usual and inject any further dynamic styles.
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. Usage In your terminal, navigate (cd) into your project's folder, then run: Terminal npx @next/codemod <transform> <path> Replacing <transform> and <path> with appropriate values. transform - name of transform path - files or directory to transform --dry Do a dry-run, no code will be edited --print Prints the changed output for comparison Next.js Codemods 13.2 Use Built-in Font built-in-next-font Terminal npx @next/codemod@latest built-in-next-font .
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-image-to-legacy-image Terminal npx @next/codemod@latest next-image-to-legacy-image . Safely renames next/image imports in existing Next.js 10, 11, or 12 applications to next/legacy/image in Next.js 13. Also renames next/future/image to next/image. For example: pages/index.js import Image1 from 'next/image' import Image2 from 'next/future/image' export default function Home() { return ( <div>
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/image' becomes 'next/image' import Image2 from 'next/image' export default function Home() { return ( <div> <Image1 src="/test.jpg" width="200" height="300" /> <Image2 src="/test.png" width="500" height="400" /> </div> ) } Migrate to the New Image Component next-image-experimental
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. Removes objectPosition prop and adds style. Removes lazyBoundary prop. Removes lazyRoot prop. Remove <a> Tags From Link Components new-link Terminal npx @next/codemod@latest new-link . Remove <a> tags inside Link Components, or add a legacyBehavior prop to Links that cannot be auto-fixed. For example: <Link href="/about"> <a>About</a> </Link> // transforms into <Link href="/about"> About </Link> <Link href="/about">
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 the old behavior for that particular link. const Component = () => <a>About</a> <Link href="/about"> <Component /> </Link> // becomes <Link href="/about" legacyBehavior> <Component /> </Link> 11 Migrate from CRA cra-to-next Terminal npx @next/codemod cra-to-next
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 gradual adoption of Next.js specific features. Please share any feedback related to this transform in this discussion. 10 Add React imports add-missing-react-import Terminal npx @next/codemod add-missing-react-import Transforms files that do not import React to include the import in order for the new React JSX transform to work. For example: my-component.js export default class Home extends React.Component { render() { return <div>Hello World</div> } } Transforms into: my-component.js import React from 'react' export default class Home extends React.Component {
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 components into named components to make sure they work with Fast Refresh. For example: my-component.js export default function () { return <div>Hello World</div> } Transforms into: my-component.js export default function MyComponent() { return <div>Hello World</div> } The component will have a camel-cased name based on the name of the file, and it also works with arrow functions. 8 Transform AMP HOC into page config withamp-to-config Terminal npx @next/codemod withamp-to-config
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 <h1>My AMP Page</h1> } export const config = { amp: true, } 6 Use withRouter url-to-withrouter Terminal npx @next/codemod url-to-withrouter Transforms the deprecated automatically injected url property on top level pages to using withRouter and the router property it injects. Read more here: https://nextjs.org/docs/messages/url-deprecated For example:
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.Component { render() { const { pathname } = this.props.router return <div>Current pathname: {pathname}</div> } } ) This is one case. All the cases that are transformed (and tested) can be found in the __testfixtures__ directory.
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 v16.8. See the Node.js documentation for more information. Next.js Version To update to Next.js version 13, run the following command using your preferred package manager: Terminal npm install next@latest react@latest react-dom@latest ESLint Version If you're using ESLint, you need to upgrade your ESLint version: Terminal npm install -D eslint-config-next@latest
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 following sections for next steps: Upgrade new features: A guide to help you upgrade to new features such as the improved Image and Link Components. Migrate from the pages to app directory: A step-by-step guide to help you incrementally migrate from the pages to the app directory. Upgrading New Features Next.js 13 introduced the new App Router with new features and conventions. The new Router is available in the app directory and co-exists with the pages directory.
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 with a temporary import: next/future/image. These improvements included less client-side JavaScript, easier ways to extend and style images, better accessibility, and native browser lazy loading. In version 13, this new behavior is now the default for next/image. There are two codemods to help you migrate to the new Image Component: next-image-to-legacy-image codemod: Safely and automatically renames next/image imports to next/legacy/image. Existing components will maintain the same behavior.
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 adding an <a> tag as a child. This behavior was added as an experimental option in version 12.2 and is now the default. In Next.js 13, <Link> always renders <a> and allows you to forward props to the underlying tag. For example: import Link from 'next/link' // Next.js 12: `<a>` has to be nested otherwise it's excluded <Link href="/about"> <a>About</a> </Link> // Next.js 13: `<Link>` always renders `<a>` under the hood
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 migration: Move any beforeInteractive scripts you previously included in _document.js to the root layout file (app/layout.tsx). The experimental worker strategy does not yet work in app and scripts denoted with this strategy will either have to be removed or modified to use a different strategy (e.g. lazyOnload). onLoad, onReady, and onError handlers will not work in Server Components so make sure to move them to a Client Component or remove them altogether. Font Optimization
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. While inlining CSS still works in pages, it does not work in app. You should use next/font instead. See the Font Optimization page to learn how to use next/font. Migrating from pages to app 🎥 Watch: Learn how to incrementally adopt the App Router → YouTube (16 minutes). Moving to the App Router may be the first time using React features that Next.js builds on top of such as Server Components, Suspense, and more. When combined with new Next.js features such as special files and layouts, migration means new concepts, mental models, and behavioral changes to learn.
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. Use nested folders to define routes and a special page.js file to make a route segment publicly accessible. Learn more. Special file conventions are used to create UI for each route segment. The most common special files are page.js and layout.js. Use page.js to define UI unique to a route. Use layout.js to define UI that is shared across multiple routes. .js, .jsx, or .tsx file extensions can be used for special files. You can colocate other files inside the app directory such as components, styles, tests, and more. 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 more granular error.js special files. Learn more. pages/404.js has been replaced with the not-found.js file. pages/api/* currently remain inside the pages directory. Step 1: Creating the app directory Update to the latest Next.js version (requires 13.4 or greater): npm install next@latest Then, create a new app directory at the root of your project (or src/ directory). Step 2: Creating a Root Layout Create a new app/layout.tsx file inside the app directory. This is a root layout that will apply to all routes inside app.
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 layout. The root layout must define <html>, and <body> tags since Next.js does not automatically create them The root layout replaces the pages/_app.tsx and pages/_document.tsx files. .js, .jsx, or .tsx extensions can be used for layout files. To manage <head> HTML elements, you can use the built-in SEO support: app/layout.tsx import { Metadata } from 'next' export const metadata: Metadata = { title: 'Home',
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 should keep _app/_document while migrating to prevent your pages/* routes from breaking. Once fully migrated, you can then safely delete them. If you are using any React Context providers, they will need to be moved to a Client Component. Migrating the getLayout() pattern to Layouts (Optional) Next.js recommended adding a property to Page components to achieve per-page layouts in the pages directory. This pattern can be replaced with native support for nested layouts in the app directory.
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() { return <p>My Page</p> } Page.getLayout = function getLayout(page) { return <DashboardLayout>{page}</DashboardLayout> }After Remove the Page.getLayout property from pages/dashboard/index.js and follow the steps for migrating pages to the app directory. app/dashboard/page.js export default function Page() { return <p>My Page</p> } Move the contents of DashboardLayout into a new Client Component to retain pages directory behavior.
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 ( <div> <h2>My Dashboard</h2> {children} </div> ) } Import the DashboardLayout into a new layout.js file inside the app directory. app/dashboard/layout.js import DashboardLayout from './DashboardLayout' // This is a Server Component export default function Layout({ children }) { return <DashboardLayout>{children}</DashboardLayout> } You can incrementally move non-interactive parts of DashboardLayout.js (Client Component) into layout.js (Server Component) to reduce the amount of component JavaScript you send to the client.
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() { return ( <> <Head> <title>My page title</title> </Head> </> ) } After: app/page.tsx import { Metadata } from 'next' export const metadata: Metadata = { title: 'My Page Title', } export default function Page() { return '...' } See all metadata options. Step 4: Migrating Pages
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. The app directory uses nested folders to define routes and a special page.js file to make a route segment publicly accessible. pages Directoryapp DirectoryRouteindex.jspage.js/about.jsabout/page.js/aboutblog/[slug].jsblog/[slug]/page.js/blog/post-1 We recommend breaking down the migration of a page into two main steps: Step 1: Move the default exported Page Component into a new Client Component. Step 2: Import the new Client Component into a new page.js file inside the app directory.
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 client' directive to the top of the file (before any imports). Move the default exported page component from pages/index.js to app/home-page.tsx. app/home-page.tsx 'use client' // This is a Client Component. It receives data as props and // has access to state and effects just like Page components // in the `pages` directory. export default function HomePage({ recentPosts }) { return ( <div> {recentPosts.map((post) => ( <div key={post.id}>{post.title}</div> ))}
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 directly into the Server Component using the new data fetching APIs. See the data fetching upgrade guide for more details. app/page.tsx // Import your Client Component import HomePage from './home-page' async function getPosts() { const res = await fetch('https://...') const posts = await res.json() return posts } export default async function Page() { // Fetch data directly in a Server Component const recentPosts = await getPosts()
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 visit http://localhost:3000. You should see your existing index route, now served through the app directory. Step 5: Migrating Routing Hooks A new router has been added to support the new behavior in the app directory. In app, you should use the three new hooks imported from next/navigation: useRouter(), usePathname(), and useSearchParams(). The new useRouter hook is imported from next/navigation and has different behavior to the useRouter hook in pages which is imported from next/router.
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 hook instead. You can use useSearchParams and usePathname together to listen to page changes. See the Router Events section for more details. These new hooks are only supported in Client Components. They cannot be used in Server Components. app/example-client-component.tsx 'use client' import { useRouter, usePathname, useSearchParams } from 'next/navigation' export default function ExampleClientComponent() { const router = useRouter() const pathname = usePathname() const searchParams = useSearchParams() // ... } In addition, the new useRouter hook has the following changes:
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. basePath has been removed. The alternative will not be part of useRouter. It has not yet been implemented. asPath has been removed because the concept of as has been removed from the new router. isReady has been removed because it is no longer necessary. During static rendering, any component that uses the useSearchParams() hook will skip the prerendering step and instead be rendered on the client at runtime. View the useRouter() API reference. Step 6: Migrating Data Fetching Methods
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. app/page.tsx export default async function Page() { // This request should be cached until manually invalidated. // Similar to `getStaticProps`. // `force-cache` is the default and can be omitted. const staticData = await fetch(`https://...`, { cache: 'force-cache' }) // This request should be refetched on every request. // Similar to `getServerSideProps`. const dynamicData = await fetch(`https://...`, { cache: 'no-store' })
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, getServerSideProps is used to fetch data on the server and forward props to the default exported React component in the file. The initial HTML for the page is prerendered from the server, followed by "hydrating" the page in the browser (making it interactive). pages/dashboard.js // `pages` directory export async function getServerSideProps() { const res = await fetch(`https://...`) const projects = await res.json()
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 React components using Server Components. This allows us to send less JavaScript to the client, while maintaining the rendered HTML from the server. By setting the cache option to no-store, we can indicate that the fetched data should never be cached. This is similar to getServerSideProps in the pages directory. app/dashboard/page.tsx // `app` directory // This function can be named anything async function getProjects() {
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((project) => ( <li key={project.id}>{project.name}</li> ))} </ul> ) } Accessing Request Object In the pages directory, you can retrieve request-based data based on the Node.js HTTP API. For example, you can retrieve the req object from getServerSideProps and use it to retrieve the request's cookies and headers. pages/index.js // `pages` directory export async function getServerSideProps({ req, query }) {
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: headers(): Based on the Web Headers API, and can be used inside Server Components to retrieve request headers. cookies(): Based on the Web Cookies API, and can be used inside Server Components to retrieve cookies. app/page.tsx // `app` directory import { cookies, headers } from 'next/headers' async function getData() { const authHeader = headers().get('authorization') return '...' } export default async function Page() {
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 directory, the getStaticProps function is used to pre-render a page at build time. This function can be used to fetch data from an external API or directly from a database, and pass this data down to the entire page as it's being generated during the build. pages/index.js // `pages` directory export async function getStaticProps() { const res = await fetch(`https://...`) const projects = await res.json() return { props: { projects } } }
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 getStaticProps in the pages directory. app/page.js // `app` directory // This function can be named anything async function getProjects() { const res = await fetch(`https://...`) const projects = await res.json() return projects } export default async function Index() { const projects = await getProjects() return projects.map((project) => <div>{project.name}</div>) } Dynamic paths (getStaticPaths)
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: [{ params: { id: '1' } }, { params: { id: '2' } }], } } export async function getStaticProps({ params }) { const res = await fetch(`https://.../posts/${params.id}`) const post = await res.json() return { props: { post } } } export default function Post({ post }) { return <PostLayout post={post} /> }
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 segments instead of an array of nested param objects or a string of resolved paths. app/posts/[id]/page.js // `app` directory import PostLayout from '@/components/post-layout' export async function generateStaticParams() { return [{ id: '1' }, { id: '2' }] } async function getPost(params) { const res = await fetch(`https://.../posts/${params.id}`) const post = await res.json() return post } export default async function Post({ params }) {
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, which sits better alone now that getStaticProps and getServerSideProps are no longer necessary. The Paths suffix is replaced by Params, which is more appropriate for nested routing with multiple dynamic segments. Replacing fallback In the pages directory, the fallback property returned from getStaticPaths is used to define the behavior of a page that isn't pre-rendered at build time. This property can be set to true to show a fallback page while the page is being generated, false to show a 404 page, or blocking to generate the page at request time.
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 controls how params outside of generateStaticParams are handled: true: (default) Dynamic segments not included in generateStaticParams are generated on demand. false: Dynamic segments not included in generateStaticParams will return a 404. This replaces the fallback: true | false | 'blocking' option of getStaticPaths in the pages directory. The fallback: 'blocking' option is not included in dynamicParams because the difference between 'blocking' and true is negligible with streaming. app/posts/[id]/page.js // `app` directory
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 true (the default), when a route segment is requested that hasn't been generated, it will be server-rendered and cached as static data on success. Incremental Static Regeneration (getStaticProps with revalidate) In the pages directory, the getStaticProps function allows you to add a revalidate field to automatically regenerate a page after a certain amount of time. This is called Incremental Static Regeneration (ISR) and helps you update static content without redeploying. pages/index.js // `pages` directory
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} /> </Layout> ) } In the app directory, data fetching with fetch() can use revalidate, which will cache the request for the specified amount of seconds. app/page.js // `app` directory async function getPosts() { const res = await fetch(`https://.../posts`, { next: { revalidate: 60 } }) const data = await res.json() return data.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 Handlers in the app directory. Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs. app/api/route.ts export async function GET(request: Request) {} Good to know: If you previously used API routes to call an external API from the client, you can now use Server Components instead to securely fetch data. Learn more about data fetching. Step 7: Styling
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 Tailwind CSS, you'll need to add the app directory to your tailwind.config.js file: tailwind.config.js module.exports = { content: [ './app/**/*.{js,ts,jsx,tsx,mdx}', // <-- Add this line './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', ], } You'll also need to import your global styles in your app/layout.js file:
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 provides Codemod transformations to help upgrade your codebase when a feature is deprecated. See Codemods for more information.
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 }) { return ( <> <section>{children}</section> <Script src="https://example.com/script.js" /> </> ) }The third-party script is fetched when the folder route (e.g. dashboard/page.js) or any nested route (e.g. dashboard/settings/page.js) is accessed by the user. Next.js will ensure the script will only load once, even if a user navigates between multiple routes in the same layout. Application Scripts
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>{children}</body> <Script src="https://example.com/script.js" /> </html> ) } This script will load and execute when any route in your application is accessed. Next.js will ensure the script will only load once, even if a user navigates between multiple pages. Recommendation: We recommend only including third-party scripts in specific pages or layouts in order to minimize any unnecessary impact to performance. Strategy
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 script early but after some hydration on the page occurs. lazyOnload: Load the script later during browser idle time. worker: (experimental) Load the script in a web worker. Refer to the next/script API reference documentation to learn more about each strategy and their use cases. Offloading Scripts To A Web Worker (Experimental) Warning: The worker strategy is not yet stable and does not yet work with the app directory. Use with caution. Scripts that use the worker strategy are offloaded and executed in a web worker with Partytown. This can improve the performance of your site by dedicating the main thread to the rest of your application code.
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
e828fcbbfa62-2