id
stringlengths
14
15
text
stringlengths
49
1.09k
source
stringlengths
46
101
092d651651e2-3
Dynamic Data Fetching Dynamic data fetches are fetch() requests that specifically opt out of caching behavior by setting the cache option to 'no-store' or revalidate to 0. The caching options for all fetch requests in a layout or page can also be set using the segment config object. To learn more about Dynamic Data Fetching, see the Data Fetching page.
https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering
d0539c74aec9-0
Edge and Node.js Runtimes In the context of Next.js, "runtime" refers to the set of libraries, APIs, and general functionality available to your code during execution. Next.js has two server runtimes where you can render parts of your application code: Node.js Runtime Edge Runtime Each runtime has its own set of APIs. Please refer to the Node.js Docs and Edge Docs for the full list of available APIs. Both runtimes can also support streaming depending on your deployment infrastructure. By default, the app directory uses the Node.js runtime. However, you can opt into different runtimes (e.g. Edge) on a per-route basis. Runtime Differences There are many considerations to make when choosing a runtime. This table shows the major differences at a glance. If you want a more in-depth analysis of the differences, check out the sections below.
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
d0539c74aec9-1
NodeServerlessEdgeCold Boot/~250msInstantHTTP StreamingYesYesYesIOAllAllfetchScalability/HighHighestSecurityNormalHighHighLatencyNormalLowLowestnpm PackagesAllAllA smaller subset Edge Runtime In Next.js, the lightweight Edge Runtime is a subset of available Node.js APIs. The Edge Runtime is ideal if you need to deliver dynamic, personalized content at low latency with small, simple functions. The Edge Runtime's speed comes from its minimal use of resources, but that can be limiting in many scenarios. For example, code executed in the Edge Runtime on Vercel cannot exceed between 1 MB and 4 MB, this limit includes imported packages, fonts and files, and will vary depending on your deployment infrastructure. Node.js Runtime Using the Node.js runtime gives you access to all Node.js APIs, and all npm packages that rely on them. However, it's not as fast to start up as routes using the Edge runtime.
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
d0539c74aec9-2
Deploying your Next.js application to a Node.js server will require managing, scaling, and configuring your infrastructure. Alternatively, you can consider deploying your Next.js application to a serverless platform like Vercel, which will handle this for you. Serverless Node.js Serverless is ideal if you need a scalable solution that can handle more complex computational loads than the Edge Runtime. With Serverless Functions on Vercel, for example, your overall code size is 50MB including imported packages, fonts, and files. The downside compared to routes using the Edge is that it can take hundreds of milliseconds for Serverless Functions to boot up before they begin processing requests. Depending on the amount of traffic your site receives, this could be a frequent occurrence as the functions are not frequently "warm". Examples Segment Runtime Option
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
d0539c74aec9-3
Examples Segment Runtime Option You can specify a runtime for individual route segments in your Next.js application. To do so, declare a variable called runtime and export it. The variable must be a string, and must have a value of either 'nodejs' or 'edge' runtime.The following example demonstrates a page route segment that exports a runtime with a value of 'edge':app/page.tsx export const runtime = 'edge' // 'nodejs' (default) | 'edge'You can also define runtime on a layout level, which will make all routes under the layout run on the edge runtime:app/layout.tsx export const runtime = 'edge' // 'nodejs' (default) | 'edge'If the segment runtime is not set, the default nodejs runtime will be used. You do not need to use the runtime option if you do not plan to change from the Node.js runtime.
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
175f38087dac-0
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
175f38087dac-1
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
175f38087dac-2
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
175f38087dac-3
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
175f38087dac-4
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
175f38087dac-5
</> ) } 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
175f38087dac-6
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
175f38087dac-7
))} </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
175f38087dac-8
}: { 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
175f38087dac-9
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
175f38087dac-10
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
175f38087dac-11
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
2a4a233cbb5c-0
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
2a4a233cbb5c-1
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
2a4a233cbb5c-2
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
2a4a233cbb5c-3
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
2a4a233cbb5c-4
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
2a4a233cbb5c-5
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
2a4a233cbb5c-6
} 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
2a4a233cbb5c-7
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
2a4a233cbb5c-8
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
66d202fb49eb-0
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
66d202fb49eb-1
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
66d202fb49eb-2
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
66d202fb49eb-3
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
66d202fb49eb-4
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
46ac516751e2-0
Server ActionsServer Actions are an alpha feature in Next.js, built on top of React Actions. They enable server-side data mutations, reduced client-side JavaScript, and progressively enhanced forms. They can be defined inside Server Components and/or called from Client Components: With Server Components: app/add-to-cart.js import { cookies } from 'next/headers' // Server action defined inside a Server Component export default function AddToCart({ productId }) { async function addItem(data) { 'use server' const cartId = cookies().get('cartId')?.value await saveToDb({ cartId, data }) } return ( <form action={addItem}> <button type="submit">Add to Cart</button> </form> ) } With Client Components: app/actions.js 'use server' export async function addItem(data) {
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-1
app/actions.js 'use server' export async function addItem(data) { const cartId = cookies().get('cartId')?.value await saveToDb({ cartId, data }) } app/add-to-cart.js 'use client' import { addItem } from './actions.js' // Server Action being called inside a Client Component export default function AddToCart({ productId }) { return ( <form action={addItem}> <button type="submit">Add to Cart</button> </form> ) } Good to know: Using Server Actions will opt into running the React experimental channel. React Actions, useOptimistic, and useFormStatus are not a Next.js or React Server Components specific features.
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-2
Next.js integrates React Actions into the Next.js router, bundler, and caching system, including adding data mutation APIs like revalidateTag and revalidatePath. Convention You can enable Server Actions in your Next.js project by enabling the experimental serverActions flag. next.config.js module.exports = { experimental: { serverActions: true, }, } Creation Server Actions can be defined in two places: Inside the component that uses it (Server Components only) In a separate file (Client and Server Components), for reusability. You can define multiple Server Actions in a single file. With Server Components Create a Server Action by defining an asynchronous function with the "use server" directive at the top of the function body. This function should have serializable arguments and a serializable return value based on the React Server Components protocol. app/server-component.js export default function ServerComponent() { async function myAction() {
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-3
app/server-component.js export default function ServerComponent() { async function myAction() { 'use server' // ... } } With Client Components If you're using a Server Action inside a Client Component, create your action in a separate file with the "use server" directive at the top of the file. Then, import the Server Action into your Client Component: app/actions.js 'use server' export async function myAction() { // ... } app/client-component.js 'use client' import { myAction } from './actions' export default function ClientComponent() { return ( <form action={myAction}> <button type="submit">Add to Cart</button> </form> ) }
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-4
</form> ) } Good to know: When using a top-level "use server" directive, all exports below will be considered Server Actions. You can have multiple Server Actions in a single file. Invocation You can invoke Server Actions using the following methods: Using action: React's action prop allows invoking a Server Action on a <form> element. Using formAction: React's formAction prop allows handling <button>, <input type="submit">, and <input type="image"> elements in a <form>. Custom Invocation with startTransition: Invoke Server Actions without using action or formAction by using startTransition. This method disables Progressive Enhancement. action You can use React's action prop to invoke a Server Action on a form element. Server Actions passed with the action prop act as asynchronous side effects in response to user interaction. app/add-to-cart.js import { cookies } from 'next/headers'
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-5
app/add-to-cart.js import { cookies } from 'next/headers' export default function AddToCart({ productId }) { async function addItem(data) { 'use server' const cartId = cookies().get('cartId')?.value await saveToDb({ cartId, data }) } return ( <form action={addItem}> <button type="submit">Add to Cart</button> </form> ) } Good to know: An action is similar to the HTML primitive action formAction You can use formAction prop to handle Form Actions on elements such as button, input type="submit", and input type="image". The formAction prop takes precedence over the form's action. app/form.js export default function Form() { async function handleSubmit() { 'use server' // ... }
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-6
async function handleSubmit() { 'use server' // ... } async function submitImage() { 'use server' // ... } return ( <form action={handleSubmit}> <input type="text" name="name" /> <input type="image" formAction={submitImage} /> <button type="submit">Submit</button> </form> ) } Good to know: A formAction is the HTML primitive formaction. React now allows you to pass functions to this attribute. Custom invocation using startTransition You can also invoke Server Actions without using action or formAction. You can achieve this by using startTransition provided by the useTransition hook, which can be useful if you want to use Server Actions outside of forms, buttons, or inputs.
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-7
Good to know: Using startTransition disables the out-of-the-box Progressive Enhancement. 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> ) } app/actions.js 'use server' export async function addItem(id) { await addItemToDb(id) // Marks all product pages for revalidating revalidatePath('/product/[id]') } Custom invocation without startTransition If you aren't doing Server Mutations, you can directly pass the function as a prop like any other function.
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-8
app/posts/[id]/page.tsx import kv from '@vercel/kv' import LikeButton from './like-button' export default function Page({ params }: { params: { id: string } }) { async function increment() { 'use server' await kv.incr(`post:id:${params.id}`) } return <LikeButton increment={increment} /> } app/post/[id]/like-button.tsx 'use client' export default function LikeButton({ increment, }: { increment: () => Promise<void> }) { return ( <button onClick={async () => { await increment() }} > Like </button> ) } Enhancements Experimental useOptimistic
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-9
</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
46ac516751e2-10
) 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
46ac516751e2-11
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
46ac516751e2-12
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
46ac516751e2-13
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
46ac516751e2-14
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
46ac516751e2-15
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
46ac516751e2-16
</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
46ac516751e2-17
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
46ac516751e2-18
'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
46ac516751e2-19
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
64d4e2b4532d-0
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
64d4e2b4532d-1
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
64d4e2b4532d-2
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
64d4e2b4532d-3
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
64e8c07c73bb-0
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
64e8c07c73bb-1
'./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
64e8c07c73bb-2
// 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
8945e7d1627d-0
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
8945e7d1627d-1
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
8945e7d1627d-2
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
8945e7d1627d-3
}) { 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 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
8945e7d1627d-4
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
8945e7d1627d-5
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
8945e7d1627d-6
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
af7a2f69c782-0
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
af7a2f69c782-1
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
f6dc9a7dd197-0
Image Optimization Examples Image Component According to Web Almanac, images account for a huge portion of the typical website’s page weight and can have a sizable impact on your website's LCP performance. The Next.js Image component extends the HTML <img> element with features for automatic image optimization: Size Optimization: Automatically serve correctly sized images for each device, using modern image formats like WebP and AVIF. Visual Stability: Prevent layout shift automatically when images are loading. Faster Page Loads: Images are only loaded when they enter the viewport using native browser lazy loading, with optional blur-up placeholders. Asset Flexibility: On-demand image resizing, even for images stored on remote servers 🎥 Watch: Learn more about how to use next/image → YouTube (9 minutes). Usage import Image from 'next/image' You can then define the src for your image (either local or remote). Local Images
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-1
You can then define the src for your image (either local or remote). Local Images To use a local image, import your .jpg, .png, or .webp image files. Next.js will automatically determine the width and height of your image based on the imported file. These values are used to prevent Cumulative Layout Shift while your image is loading. app/page.js import Image from 'next/image' import profilePic from './me.png' export default function Page() { return ( <Image src={profilePic} alt="Picture of the author" // width={500} automatically provided // height={500} automatically provided // blurDataURL="data:..." automatically provided // placeholder="blur" // Optional blur-up while loading /> ) }
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-2
/> ) } Warning: Dynamic await import() or require() are not supported. The import must be static so it can be analyzed at build time. Remote Images To use a remote image, the src property should be a URL string. Since Next.js does not have access to remote files during the build process, you'll need to provide the width, height and optional blurDataURL props manually. The width and height attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in. The width and height do not determine the rendered size of the image file. Learn more about Image Sizing. app/page.js import Image from 'next/image' export default function Page() { return ( <Image src="https://s3.amazonaws.com/my-bucket/profile.png" alt="Picture of the author" width={500} height={500}
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-3
width={500} height={500} /> ) } To safely allow optimizing images, define a list of supported URL patterns in next.config.js. Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket: next.config.js module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 's3.amazonaws.com', port: '', pathname: '/my-bucket/**', }, ], }, } Learn more about remotePatterns configuration. If you want to use relative URLs for the image src, use a loader. Domains
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-4
Domains Sometimes you may want to optimize a remote image, but still use the built-in Next.js Image Optimization API. To do this, leave the loader at its default setting and enter an absolute URL for the Image src prop. To protect your application from malicious users, you must define a list of remote hostnames you intend to use with the next/image component. Learn more about remotePatterns configuration. Loaders Note that in the example earlier, a partial URL ("/me.png") is provided for a remote image. This is possible because of the loader architecture. A loader is a function that generates the URLs for your image. It modifies the provided src, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic srcset generation, so that visitors to your site will be served an image that is the right size for their viewport.
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-5
The default loader for Next.js applications uses the built-in Image Optimization API, which optimizes images from anywhere on the web, and then serves them directly from the Next.js web server. If you would like to serve your images directly from a CDN or image server, you can write your own loader function with a few lines of JavaScript. You can define a loader per-image with the loader prop, or at the application level with the loaderFile configuration. Priority You should add the priority property to the image that will be the Largest Contentful Paint (LCP) element for each page. Doing so allows Next.js to specially prioritize the image for loading (e.g. through preload tags or priority hints), leading to a meaningful boost in LCP.
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-6
The LCP element is typically the largest image or text block visible within the viewport of the page. When you run next dev, you'll see a console warning if the LCP element is an <Image> without the priority property. Once you've identified the LCP image, you can add the property like this: app/page.js import Image from 'next/image' import profilePic from '../public/me.png' export default function Page() { return <Image src={profilePic} alt="Picture of the author" priority /> } See more about priority in the next/image component documentation. Image Sizing
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-7
} See more about priority in the next/image component documentation. Image Sizing One of the ways that images most commonly hurt performance is through layout shift, where the image pushes other elements around on the page as it loads in. This performance problem is so annoying to users that it has its own Core Web Vital, called Cumulative Layout Shift. The way to avoid image-based layout shifts is to always size your images. This allows the browser to reserve precisely enough space for the image before it loads. Because next/image is designed to guarantee good performance results, it cannot be used in a way that will contribute to layout shift, and must be sized in one of three ways: Automatically, using a static import Explicitly, by including a width and height property Implicitly, by using fill which causes the image to expand to fill its parent element. What if I don't know the size of my images?
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-8
What if I don't know the size of my images? If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do: Use fill The fill prop allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page along sizes prop to match any media query break points. You can also use object-fit with fill, contain, or cover, and object-position to define how the image should occupy that space. Normalize your images If you're serving images from a source that you control, consider modifying your image pipeline to normalize the images to a specific size. Modify your API calls If your application is retrieving image URLs using an API call (such as to a CMS), you may be able to modify the API call to return the image dimensions along with the URL.
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-9
If none of the suggested methods works for sizing your images, the next/image component is designed to work well on a page alongside standard <img> elements. Styling Styling the Image component is similar to styling a normal <img> element, but there are a few guidelines to keep in mind: Use className or style, not styled-jsx. In most cases, we recommend using the className prop. This can be an imported CSS Module, a global stylesheet, etc. You can also use the style prop to assign inline styles. You cannot use styled-jsx because it's scoped to the current component (unless you mark the style as global). When using fill, the parent element must have position: relative This is necessary for the proper rendering of the image element in that layout mode. When using fill, the parent element must have display: block This is the default for <div> elements but should be specified otherwise. Examples Responsive
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-10
This is the default for <div> elements but should be specified otherwise. Examples Responsive import Image from 'next/image' import mountains from '../public/mountains.jpg' export default function Responsive() { return ( <div style={{ display: 'flex', flexDirection: 'column' }}> <Image alt="Mountains" // Importing an image will // automatically set the width and height src={mountains} sizes="100vw" // Make the image display full width style={{ width: '100%', height: 'auto', }} /> </div> ) } Fill Container import Image from 'next/image' import mountains from '../public/mountains.jpg' export default function Fill() { return ( <div style={{
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-11
export default function Fill() { return ( <div style={{ display: 'grid', gridGap: '8px', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, auto))', }} > <div style={{ position: 'relative', height: '400px' }}> <Image alt="Mountains" src={mountains} fill sizes="(min-width: 808px) 50vw, 100vw" style={{ objectFit: 'cover', // cover, contain, none }} /> </div> {/* And more images in the grid... */} </div> ) } Background Image import Image from 'next/image' import mountains from '../public/mountains.jpg' export default function Background() {
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-12
import mountains from '../public/mountains.jpg' export default function Background() { return ( <Image alt="Mountains" src={mountains} placeholder="blur" quality={100} fill sizes="100vw" style={{ objectFit: 'cover', }} /> ) } For examples of the Image component used with the various styles, see the Image Component Demo. Other Properties View all properties available to the next/image component. Configuration The next/image component and Next.js Image Optimization API can be configured in the next.config.js file. These configurations allow you to enable remote images, define custom image breakpoints, change caching behavior and more. Read the full image configuration documentation for more information.
https://nextjs.org/docs/app/building-your-application/optimizing/images
43a365f70a81-0
Font Optimization next/font will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance. 🎥 Watch: Learn more about how to use next/font → YouTube (6 minutes). next/font includes built-in automatic self-hosting for any font file. This means you can optimally load web fonts with zero layout shift, thanks to the underlying CSS size-adjust property used. This new font system also allows you to conveniently use all Google Fonts with performance and privacy in mind. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to Google by the browser. Google Fonts Automatically self-host any Google Font. Fonts are included in the deployment and served from the same domain as your deployment. No requests are sent to Google by the browser.
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-1
Get started by importing the font you would like to use from next/font/google as a function. We recommend using variable fonts for the best performance and flexibility. app/layout.tsx import { Inter } from 'next/font/google' // If loading a variable font, you don't need to specify the font weight const inter = Inter({ subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={inter.className}> <body>{children}</body> </html> ) }If you can't use a variable font, you will need to specify a weight:app/layout.tsx import { Roboto } from 'next/font/google' const roboto = Roboto({ weight: '400',
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-2
const roboto = Roboto({ weight: '400', subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={roboto.className}> <body>{children}</body> </html> ) } You can specify multiple weights and/or styles by using an array: app/layout.js const roboto = Roboto({ weight: ['400', '700'], style: ['normal', 'italic'], subsets: ['latin'], display: 'swap', }) Good to know: Use an underscore (_) for font names with multiple words. E.g. Roboto Mono should be imported as Roboto_Mono. Specifying a subset
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-3
Specifying a subset Google Fonts are automatically subset. This reduces the size of the font file and improves performance. You'll need to define which of these subsets you want to preload. Failing to specify any subsets while preload is true will result in a warning. This can be done by adding it to the function call: app/layout.tsx const inter = Inter({ subsets: ['latin'] }) View the Font API Reference for more information. Using Multiple Fonts You can import and use multiple fonts in your application. There are two approaches you can take. The first approach is to create a utility function that exports a font, imports it, and applies its className where needed. This ensures the font is preloaded only when it's rendered: app/fonts.ts import { Inter, Roboto_Mono } from 'next/font/google' export const inter = Inter({ subsets: ['latin'], display: 'swap', })
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-4
subsets: ['latin'], display: 'swap', }) export const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', }) app/layout.tsx import { inter } from './fonts' export default function Layout({ children }: { children: React.ReactNode }) { return ( <html lang="en" className={inter.className}> <body> <div>{children}</div> </body> </html> ) }app/page.tsx import { roboto_mono } from './fonts' export default function Page() { return ( <> <h1 className={roboto_mono.className}>My page</h1> </> ) }
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-5
</> ) } In the example above, Inter will be applied globally, and Roboto Mono can be imported and applied as needed. Alternatively, you can create a CSS variable and use it with your preferred CSS solution: app/layout.tsx import { Inter, Roboto_Mono } from 'next/font/google' import styles from './global.css' const inter = Inter({ subsets: ['latin'], variable: '--font-inter', display: 'swap', }) const roboto_mono = Roboto_Mono({ subsets: ['latin'], variable: '--font-roboto-mono', display: 'swap', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return (
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-6
children, }: { children: React.ReactNode }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body> <h1>My App</h1> <div>{children}</div> </body> </html> ) } app/global.css html { font-family: var(--font-inter); } h1 { font-family: var(--font-roboto-mono); } In the example above, Inter will be applied globally, and any <h1> tags will be styled with Roboto Mono. Recommendation: Use multiple fonts conservatively since each new font is an additional resource the client has to download. Local Fonts
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-7
Local Fonts Import next/font/local and specify the src of your local font file. We recommend using variable fonts for the best performance and flexibility. app/layout.tsx import localFont from 'next/font/local' // Font files can be colocated inside of `app` const myFont = localFont({ src: './my-font.woff2', display: 'swap', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={myFont.className}> <body>{children}</body> </html> ) } If you want to use multiple files for a single font family, src can be an array: const roboto = localFont({ src: [ { path: './Roboto-Regular.woff2',
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-8
src: [ { path: './Roboto-Regular.woff2', weight: '400', style: 'normal', }, { path: './Roboto-Italic.woff2', weight: '400', style: 'italic', }, { path: './Roboto-Bold.woff2', weight: '700', style: 'normal', }, { path: './Roboto-BoldItalic.woff2', weight: '700', style: 'italic', }, ], }) View the Font API Reference for more information. With Tailwind CSS next/font can be used with Tailwind CSS through a CSS variable.
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-9
With Tailwind CSS next/font can be used with Tailwind CSS through a CSS variable. In the example below, we use the font Inter from next/font/google (you can use any font from Google or Local Fonts). Load your font with the variable option to define your CSS variable name and assign it to inter. Then, use inter.variable to add the CSS variable to your HTML document. app/layout.tsx import { Inter, Roboto_Mono } from 'next/font/google' const inter = Inter({ subsets: ['latin'], display: 'swap', variable: '--font-inter', }) const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', variable: '--font-roboto-mono', }) export default function RootLayout({ children, }: { children: React.ReactNode }) {
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-10
children, }: { children: React.ReactNode }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body>{children}</body> </html> ) } Finally, add the CSS variable to your Tailwind CSS config: tailwind.config.js /** @type {import('tailwindcss').Config} */ module.exports = { content: [ './pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}', './app/**/*.{js,ts,jsx,tsx}', ], theme: { extend: { fontFamily: { sans: ['var(--font-inter)'], mono: ['var(--font-roboto-mono)'], }, }, },
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-11
}, }, }, plugins: [], } You can now use the font-sans and font-mono utility classes to apply the font to your elements. Preloading When a font function is called on a page of your site, it is not globally available and preloaded on all routes. Rather, the font is only preloaded on the related routes based on the type of file where it is used: If it's a unique page, it is preloaded on the unique route for that page. If it's a layout, it is preloaded on all the routes wrapped by the layout. If it's the root layout, it is preloaded on all routes. Reusing fonts
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-12
If it's the root layout, it is preloaded on all routes. Reusing fonts Every time you call the localFont or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted. In this situation, it is recommended to do the following: Call the font loader function in one shared file Export it as a constant Import the constant in each file where you would like to use this font
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
995394ed8592-0
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
995394ed8592-1
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
995394ed8592-2
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
995394ed8592-3
This strategy is still experimental and can only be used if the nextScriptWorkers flag is enabled in next.config.js: next.config.js module.exports = { experimental: { nextScriptWorkers: true, }, } Then, run next (normally npm run dev or yarn dev) and Next.js will guide you through the installation of the required packages to finish the setup: Terminal npm run dev You'll see instructions like these: Please install Partytown by running npm install @builder.io/partytown Once setup is complete, defining strategy="worker" will automatically instantiate Partytown in your application and offload the script to a web worker. pages/home.tsx import Script from 'next/script' export default function Home() { return ( <> <Script src="https://example.com/script.js" strategy="worker" /> </> ) }
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-4
</> ) } There are a number of trade-offs that need to be considered when loading a third-party script in a web worker. Please see Partytown's tradeoffs documentation for more information. Inline Scripts Inline scripts, or scripts not loaded from an external file, are also supported by the Script component. They can be written by placing the JavaScript within curly braces: <Script id="show-banner"> {`document.getElementById('banner').classList.remove('hidden')`} </Script> Or by using the dangerouslySetInnerHTML property: <Script id="show-banner" dangerouslySetInnerHTML={{ __html: `document.getElementById('banner').classList.remove('hidden')`, }} /> Warning: An id property must be assigned for inline scripts in order for Next.js to track and optimize the script. Executing Additional Code
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-5
Executing Additional Code Event handlers can be used with the Script component to execute additional code after a certain event occurs: onLoad: Execute code after the script has finished loading. onReady: Execute code after the script has finished loading and every time the component is mounted. onError: Execute code if the script fails to load. These handlers will only work when next/script is imported and used inside of a Client Component where "use client" is defined as the first line of code:app/page.tsx 'use client' import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" onLoad={() => { console.log('Script has loaded') }} /> </> ) }Refer to the next/script API reference to learn more about each event handler and view examples.
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-6
}Refer to the next/script API reference to learn more about each event handler and view examples. Additional Attributes There are many DOM attributes that can be assigned to a <script> element that are not used by the Script component, like nonce or custom data attributes. Including any additional attributes will automatically forward it to the final, optimized <script> element that is included in the HTML. app/page.tsx import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" id="example-script" nonce="XUENAJFW" data-test="script" /> </> ) }
https://nextjs.org/docs/app/building-your-application/optimizing/scripts