new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · API reference · all subjects

functions

556 notes in this subject, read out of this brain and free to use. This is page 3 of 10.

fetch() cache matching logic

When using cache: 'force-cache', a fetch request matches on its URL, method, headers, and body. Requests that differ in any of these are cached separately.

options.cache parameter values

The cache option accepts the following values: - 'auto' (default): Next.js fetches the resource from the remote server on every request in development, but will fetch once during next build because the route will be statically prerendered. If Request-time APIs are detected on the route, Next.js will fetch the resource on every request. - 'no-store': Next.js fetches the resource from the remote server on every request, even if Request-time APIs are not detected on the route. - 'force-cache': Next.js looks for a matching request in its server-side cache. A request matches on its URL, method, headers, and body. If there is a match and it is fresh, it will be returned from the cache. If there is no match or a stale match, Next.js fetches the resource from the remote server and updates the cache. Only responses with a 200 HTTP status code are stored.

fetch() with async/await in Server Components example

export default async function Page() { let data = await fetch('https://api.vercel.app/blog') let posts = await data.json() return ( <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> ) } This example shows calling fetch with async/await directly within a Server Component to retrieve and display data.

generateSitemaps example with multiple sitemaps

This example shows how to generate multiple sitemaps using generateSitemaps: ```ts filename="app/product/sitemap.ts" import type { MetadataRoute } from 'next' import { BASE_URL } from '@/app/lib/constants' export async function generateSitemaps() { // Fetch the total number of products and calculate the number of sitemaps needed return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }] } export default async function sitemap(props: { id: Promise<string> }): Promise<MetadataRoute.Sitemap> { const id = await props.id // Google's limit is 50,000 URLs per sitemap const start = id * 50000 const end = start + 50000 const products = await getProducts( `SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}` ) return products.map((product) => ({ url: `${BASE_URL}/product/${product.id}`, lastModified: product.date, })) } ```

Google sitemap URL limit per file

Google's limit is 50,000 URLs per sitemap file. When splitting sitemaps using generateSitemaps, each sitemap should contain no more than 50,000 URLs.

generateSitemaps development URL pattern

In development, generated sitemaps can be viewed at /.../sitemap.xml/[id]. For example, /product/sitemap.xml/1. This development-only URL pattern was introduced in v13.3.2.

Generated sitemaps URL pattern

Generated sitemaps are available at the URL pattern /.../sitemap/[id].xml. For example, sitemaps for /product/sitemap.ts will be available at /product/sitemap/1.xml, /product/sitemap/2.xml, etc.

generateSitemaps function returns array of objects with id

The generateSitemaps function returns an array of objects with an id property. Each object in the array represents a separate sitemap that will be generated.

generateSitemaps v13.3.2 introduction

generateSitemaps was introduced in v13.3.2. In development, generated sitemaps can be viewed at /.../sitemap.xml/[id].

generateSitemaps v15.0.0 change: consistent URLs between development and production

As of v15.0.0, generateSitemaps now generates consistent URLs between development and production environments.

generateSitemaps v16.0.0 change: id passed as promise

As of v16.0.0, the id values returned from generateSitemaps are passed as a promise that resolves to a string to the sitemap function. The sitemap function receives props with an id field of type Promise<string>, which must be awaited to get the actual id value.

viewport with use cache directive

When viewport depends on external data but not runtime data (like cookies, headers, params, searchParams), use the 'use cache' directive to cache the viewport generation. Example: export async function generateViewport() { 'use cache'; const { width, initialScale } = await db.query('viewport-size'); return { width, initialScale } }

generateViewport recommendation

If the viewport does not depend on request information, define it using the static viewport object rather than generateViewport.

generateViewport JSDoc typing for JavaScript

In JavaScript projects, use JSDoc to type the viewport: /** @type {import("next").Viewport} */ export const viewport = { themeColor: 'black' }

viewport and generateViewport introduction version

The viewport object and generateViewport function were introduced in Next.js v14.0.0.

generateViewport TypeScript typing

The Viewport type can be imported from 'next' to add type safety. For generateViewport, the return type is Viewport. The function can also accept Props with params and searchParams typed as Promise<{...}>.

viewport themeColor HTML output

A viewport object with themeColor: 'black' generates <meta name="theme-color" content="black" /> in the HTML head. With media queries, it generates multiple meta tags, one for each media query and color pair.

viewport object export location

The viewport object is exported from a layout.jsx/layout.tsx or page.jsx/page.tsx file.

Multiple root layouts to isolate dynamic viewport

Use multiple root layouts to isolate fully dynamic viewport to specific routes while letting other routes generate a static shell.

Cache Components behavior with generateViewport

When Cache Components is enabled, generateViewport follows the same rules as other components. If viewport accesses runtime data or performs uncached data fetching, it defers to request time, which blocks page load since viewport cannot be streamed.

generateViewport with runtime data requires Suspense or instant=false

Unlike metadata, viewport cannot be streamed because it affects initial page load UI. If generateViewport depends on runtime data (cookies, headers, params, searchParams), either wrap the document body in a Suspense boundary to stream the shell immediately, or set instant = false on the segment to opt out of instant-navigation validation, blocking navigation until render completes.

generateViewport function signature with params

generateViewport receives an object parameter with params and searchParams properties. The params argument can be typed via PageProps<'/route'> or LayoutProps<'/route'> helpers depending on where generateViewport is defined.

Viewport object fields

The Viewport object supports the following fields: themeColor (string or array of {media, color} objects), width (e.g., 'device-width'), initialScale (number), maximumScale (number), userScalable (boolean), colorScheme (string like 'dark'), and interactiveWidget (less commonly used).

generateViewport themeColor field

The themeColor field in a Viewport object can be a string like 'black', or an array of objects with media queries. Each object in the array has a media property (CSS media query string) and a color property (color value). Example: [{ media: '(prefers-color-scheme: light)', color: 'cyan' }, { media: '(prefers-color-scheme: dark)', color: 'black' }]

generateViewport only in Server Components

Both the viewport object and generateViewport function exports are only supported in Server Components.

viewport object vs generateViewport

The viewport object and generateViewport function are mutually exclusive: you cannot export both from the same route segment. Use the static viewport object for static viewports, and generateViewport for dynamic ones.

generateViewport function purpose

generateViewport is a dynamic function that returns a Viewport object containing one or more viewport fields. It is used to customize the initial viewport of a page when the viewport depends on dynamic information.

notFound can be invoked in Server Components, Server Functions, and Route Handlers

notFound() can be invoked in Server Components, Server Functions, and Route Handlers.

notFound injects noindex meta tag

Next.js injects a <meta name="robots" content="noindex" /> tag when notFound() is called, so the page is not indexed by search engines.

notFound must be called in render path

The notFound() function must be called in the render path: a component, or a function a component awaits. A call left in an un-awaited promise throws where nothing catches it, and no not-found UI renders. In development the server logs '⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;404'.

notFound throws NEXT_HTTP_ERROR_FALLBACK;404

Invoking notFound() throws a NEXT_HTTP_ERROR_FALLBACK;404 error and terminates rendering of the route segment where it was thrown.

notFound version history

notFound was introduced in v13.0.0.

notFound never return type

The notFound function has a TypeScript 'never' return type, so you do not need to write 'return notFound()'. Calling it is enough because it throws an exception that stops function execution. TypeScript understands this, so a value you check first stays narrowed afterward.

notFound function

The notFound function is imported from 'next/navigation' and throws an error that renders a Next.js 404 page. It is useful for handling missing resources in your application.

notFound import from next/navigation

The notFound function is imported from the 'next/navigation' module: import { notFound } from 'next/navigation'

notFound customize UI with not-found.js file

You can customize the UI rendered by notFound() using the not-found.js file. Without one, the nearest parent not-found boundary renders, falling back to Next.js's default 404 page.

notFound in Route Handler serves 404

notFound() also works in a Route Handler, where it serves a 404 to the caller.

notFound HTTP status after streaming

When notFound() is called inside a <Suspense> boundary after streaming has started, the response has already begun streaming as a 200, and the status cannot change once streaming has started. The noindex tag keeps a soft 404 out of search results. To return a real 404 status, the resource has to be checked before the response streams.

notFound in Suspense boundary example

To keep a page's shell and loading UI visible while data loads, put the existence check inside a component wrapped in <Suspense> instead of blocking the whole route. The idiomatic place for the check is the data-access function itself, awaited by the component that needs the data.

notFound can be suppressed by try/catch

Like any exception, notFound() travels up the call stack until something catches it. A try/catch around the call suppresses it, and the not-found UI will not render. If you need to catch errors near the call, use unstable_rethrow to let the interrupt through first.

NextResponse extends Web Response API

NextResponse extends the Web Response API with additional convenience methods for working with responses in Next.js middleware and route handlers.

NextResponse.next() defensive header forwarding example

When forwarding headers, use a defensive allow-list approach. Keep only known-safe headers and discard custom x-* headers, authorization, and cookie headers. Preserve the original header name casing when forwarding.

NextResponse.next() avoid sending headers to client

NextResponse.next({ headers }) is a shorthand for sending headers from proxy to the client and is NOT good practice. Setting response headers like Content-Type can override framework expectations, leading to failed submissions or broken streaming responses. Avoid copying all incoming request headers to prevent leaking sensitive data.

NextResponse.next() with forwarded headers

NextResponse.next({ request: { headers } }) forwards modified request headers upstream to the target page, route, or server action without exposing them to the client. The forwarded headers do not reach the browser.

NextResponse.next() method

The next() method allows you to return early and continue routing. Useful for middleware that needs to pass control to the next middleware or route handler.

NextResponse.rewrite() method

Produces a response that rewrites (proxies) the given URL while preserving the original URL in the browser. The browser shows the original URL but the request is rewritten to the new URL internally.

NextResponse.json() method

Produces a response with a JSON body. Accepts a data object and an optional options object. Example: NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }) returns a JSON response with status 500.

NextResponse.cookies.delete(name)

Given a cookie name, deletes the cookie from the response. Returns true if a cookie was deleted, false if nothing was deleted.

NextResponse.cookies.has(name)

Given a cookie name, returns true if the cookie exists on the response, false otherwise.

NextResponse.cookies.getAll()

Given a cookie name, returns an array of all cookies with that name. If no name is given, returns all cookies on the response.

NextResponse.cookies.get(name)

Given a cookie name, returns the value of the cookie as an object with properties like name, value, and Path. Returns undefined if the cookie is not found. If multiple cookies exist with the same name, returns the first one.

NextResponse defensive header forwarding code

Example of defensive header forwarding that creates an allow-list: const incoming = new Headers(request.headers); const forwarded = new Headers(); for (const [name, value] of incoming) { const headerName = name.toLowerCase(); if (!headerName.startsWith('x-') && headerName !== 'authorization' && headerName !== 'cookie') { forwarded.set(name, value); } } return NextResponse.next({ request: { headers: forwarded } });

NextResponse.next() with modified headers example

Example showing how to forward modified request headers upstream: const newHeaders = new Headers(request.headers); newHeaders.set('x-version', '123'); return NextResponse.next({ request: { headers: newHeaders } });

NextResponse.redirect() method

Produces a response that redirects to a given URL. Takes a URL object created from the Web API URL class. Example: NextResponse.redirect(new URL('/new', request.url)).

Default metadata tags

Two default meta tags are always added even if metadata is not defined: meta charset tag set to utf-8, and meta viewport tag set to 'width=device-width, initial-scale=1'.

generateMetadata function definition

generateMetadata is an async function that returns a Metadata object. It accepts props containing params and searchParams (both Promises), and a parent parameter that is a Promise of ResolvingMetadata. The function is used for dynamic metadata that depends on route parameters, external data, or parent segment metadata. It must be exported from layout.js or page.js files.

metadata object vs generateMetadata function

The metadata object is used for static metadata exported from layout.js or page.js. generateMetadata is used for dynamic metadata. You cannot export both the metadata object and generateMetadata function from the same route segment.

File-based metadata priority

File-based metadata has higher priority and will override the metadata object and generateMetadata function.

generateMetadata is Server Component only

generateMetadata and the metadata export are only supported in Server Components because metadata must be resolved on the server before the page component is rendered. This allows Next.js to include the metadata in the initial HTML response. If you need Client Component features, keep your page as a Server Component and move Client Component logic to a separate file with 'use client' directive.

generateMetadata parameters: params and searchParams types

In generateMetadata, params is a Promise<{ [key: string]: string | string[] }> containing dynamic route parameters from root segment down to the current segment. searchParams is a Promise<{ [key: string]: string | string[] | undefined }> containing the URL search parameters. Both are only available in page.js, not layout.js for searchParams.

Give your agent this brain