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 2 of 10.

cookies function version history

In version v15.0.0-RC, cookies became an async function. A codemod is available for upgrading. In v13.0.0, cookies was introduced.

Deleting a cookie with maxAge 0 example

'use server' import { cookies } from 'next/headers' export async function deleteCookie(data) { const cookieStore = await cookies() cookieStore.set('name', 'value', { maxAge: 0 }) }

Deleting a cookie with delete method example

'use server' import { cookies } from 'next/headers' export async function deleteCookie(data) { const cookieStore = await cookies() cookieStore.delete('name') }

Checking if a cookie exists example

import { cookies } from 'next/headers' export default async function Page() { const cookieStore = await cookies() const hasCookie = cookieStore.has('theme') return '...' }

Setting a cookie example

'use server' import { cookies } from 'next/headers' export async function create(data) { const cookieStore = await cookies() cookieStore.set('name', 'lee') // or cookieStore.set('name', 'lee', { secure: true }) // or cookieStore.set({ name: 'name', value: 'lee', httpOnly: true, path: '/', }) }

cookies function is async and requires await

The cookies function is an async function that returns a promise. You must use async/await or React's use function to access cookies. In version 14 and earlier, cookies was a synchronous function, but in Next.js 15 it became asynchronous.

Getting a single cookie example

import { cookies } from 'next/headers' export default async function Page() { const cookieStore = await cookies() const theme = cookieStore.get('theme') return '...' }

Cookie behavior in Server Functions

After you set or delete a cookie in a Server Function, Next.js can return both the updated UI and new data in a single server roundtrip when the function is used as a Server Action. The UI is not unmounted, but effects that depend on data from the server will re-run. To refresh cached data, call revalidatePath or revalidateTag inside the function.

Reading vs setting cookies in Server Components

Reading cookies works in Server Components because you're accessing the cookie data that the client's browser sends to the server in HTTP request headers. Setting cookies is not supported during Server Component rendering. To modify cookies, invoke a Server Function from the client or use a Route Handler.

delete method restrictions

The .delete method can only be called in a Server Function or Route Handler. It can only delete cookies from the same domain from which .set is called. For wildcard domains, the specific subdomain must be an exact match. The code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete.

cookies with Cache Components and Suspense

With Cache Components, calling cookies() outside of a Suspense boundary prevents the route from being prerendered.

cookies is a Request-time API causing dynamic rendering

The cookies function is a Request-time API whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into dynamic rendering.

cookies methods reference

The cookies function provides the following methods: get(name) returns an Object with the name and value; getAll() returns an Array of objects with all cookies; has(name) returns a Boolean; set(name, value, options) sets the outgoing request cookie with no return; delete(name) deletes the cookie with no return; toString() returns a String representation of the cookies.

cookies set options reference

When calling set(name, value, options), the options object supports: name (String) - specifies the name of the cookie; value (String) - specifies the value to be stored; expires (Date) - defines the exact date when the cookie will expire; maxAge (Number) - sets the cookie's lifespan in seconds; domain (String) - specifies the domain where the cookie is available; path (String, default: '/') - limits the cookie's scope to a specific path; secure (Boolean) - ensures the cookie is sent only over HTTPS; httpOnly (Boolean) - restricts the cookie to HTTP requests, preventing client-side access; sameSite (Boolean, 'lax', 'strict', 'none') - controls cross-site request behavior; priority (String: 'low', 'medium', 'high') - specifies the cookie's priority; partitioned (Boolean) - indicates whether the cookie is partitioned. Only path has a default value.

draftMode version history

In v15.0.0-RC, draftMode became an async function (a codemod is available for upgrading). draftMode was introduced in v13.4.0.

Draft Mode session ends when browser closes

By default, the Draft Mode session ends when the browser is closed. To disable Draft Mode manually, call the disable() method in a Route Handler.

draftMode with caching directives invalidates cache

When Draft Mode is enabled, all functions and components under a caching directive scope re-execute on every request and results are not saved to the cache. This ensures draft content is always fresh.

draftMode enable/disable throws error in use cache scope

Calling enable() or disable() inside a caching directive scope will throw an error.

draftMode isEnabled readable in use cache scope

The isEnabled property is readable inside a caching directive scope. Other runtime APIs like cookies() and headers() are not allowed inside caching directive scopes, even when Draft Mode is active.

draftMode local testing requirements

To test Draft Mode locally over HTTP, your browser will need to allow third-party cookies and local storage access.

draftMode bypass cookie generation

A new bypass cookie value (__prerender_bypass) will be generated each time you run next build. This ensures the bypass cookie cannot be guessed.

draftMode disable() requires prefetch={false} on Link

If disabling Draft Mode by calling disable() in a Route Handler, when calling the route using the Link component, you must pass prefetch={false} to prevent accidentally deleting the cookie on prefetch.

draftMode isEnabled check example

import { draftMode } from 'next/headers' export default async function Page() { const { isEnabled } = await draftMode() return ( <main> <h1>My Blog Post</h1> <p>Draft Mode is currently {isEnabled ? 'Enabled' : 'Disabled'}</p> </main> ) }

draftMode disable() example

import { draftMode } from 'next/headers' export async function GET(request: Request) { const draft = await draftMode() draft.disable() return new Response('Draft mode is disabled') }

draftMode enable() example

import { draftMode } from 'next/headers' export async function GET(request: Request) { const draft = await draftMode() draft.enable() return new Response('Draft mode is enabled') }

draftMode methods and properties

draftMode returns an object with the following: isEnabled (boolean indicating if Draft Mode is enabled), enable() (enables Draft Mode in a Route Handler by setting a cookie called __prerender_bypass), disable() (disables Draft Mode in a Route Handler by deleting a cookie).

draftMode import and usage

Import draftMode from 'next/headers'. Call it as an async function in a Server Component to get an object with isEnabled property and enable/disable methods.

draftMode is an async function

The draftMode function from 'next/headers' is an asynchronous function that returns a promise. You must use async/await or React's use function. In Next.js 15, it can still be accessed synchronously for backwards compatibility, but this behavior will be deprecated in the future.

generateImageMetadata version 16.0.0 changes

In version 16.0.0, the id passed to the Image generation function changed to be a promise that resolves to string or number. Also in version 16.0.0, the params passed to the Image generation function changed to be a promise that resolves to an object.

generateImageMetadata example with external data

This example shows using generateImageMetadata with external data to generate multiple Open Graph images. The function calls getOGImages(params.id) and maps the results to return metadata objects with id, size, alt, and contentType. The default export Image component receives both params and id as promises and awaits them to generate the image.

generateImageMetadata params prop for image function

The image generation function can receive an optional params prop which is a promise that resolves to an object containing the dynamic route parameters from the root segment down to the segment the image is colocated in.

generateImageMetadata id prop type

The id prop passed to the image generation function is a promise that resolves to the id value from one of the items returned by generateImageMetadata. The id will be a string or number depending on what was returned from generateImageMetadata.

generateImageMetadata return value

The generateImageMetadata function should return an array of objects containing the image's metadata. Each item must include an id value which will be passed as a promise to the props of the image generating function. The metadata object can include: id (string, required), alt (string), size ({ width: number; height: number }), and contentType (string).

generateImageMetadata params parameter

The generateImageMetadata function accepts an optional params parameter containing the dynamic route parameters object from the root segment down to the segment generateImageMetadata is called from. For route app/shop/[slug]/icon.js with URL /shop/1, params would be { slug: '1' }. For route app/shop/icon.js with URL /shop, params would be undefined.

generateImageMetadata function overview

generateImageMetadata is a function that generates different versions of one image or returns multiple images for one route segment. It is useful for avoiding hard-coding metadata values, such as for icons.

generateImageMetadata working example

```tsx import { ImageResponse } from 'next/og' export function generateImageMetadata() { return [ { contentType: 'image/png', size: { width: 48, height: 48 }, id: 'small', }, { contentType: 'image/png', size: { width: 72, height: 72 }, id: 'medium', }, ] } export default async function Icon({ id }: { id: Promise<string | number> }) { const iconId = await id return new ImageResponse( ( <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 88, background: '#000', color: '#fafafa', }} > Icon {iconId} </div> ) ) } ``` This example shows generateImageMetadata returning an array of image metadata objects with different sizes, and the Image component receiving the id as a promise that must be awaited before use.

forbidden function example: role-based route protection

Example showing how to use forbidden() to restrict access based on user roles: ```tsx import { verifySession } from '@/app/lib/dal' import { forbidden } from 'next/navigation' export default async function AdminPage() { const session = await verifySession() if (session.role !== 'admin') { forbidden() } return ( <main> <h1>Admin Dashboard</h1> <p>Welcome, {session.user.name}!</p> </main> ) } ```

forbidden in un-awaited promise logs unhandledRejection

A forbidden() call left in an un-awaited promise throws where nothing catches it, so no forbidden UI renders. In development the server logs ⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;403. Always await the function that may call forbidden().

try/catch suppresses forbidden interrupt

A try/catch block around the forbidden() call suppresses the interrupt and no forbidden UI renders. Use unstable_rethrow to let the interrupt through.

forbidden has never return type in TypeScript

The forbidden() function has a TypeScript never return type, meaning execution stops after it is called. You do not need to write return forbidden() because it throws and stops execution.

forbidden injects noindex robots meta tag

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

forbidden function throws 403 error

The forbidden() function throws a NEXT_HTTP_ERROR_FALLBACK;403 error and terminates rendering of the route segment where it was thrown. It renders a Next.js 403 page and is useful for handling authorization errors in applications.

forbidden must be called in render path

The forbidden() 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 forbidden UI renders.

forbidden cannot be called in root layout

The forbidden() function cannot be called in the root layout.

forbidden contexts: Server Components, Server Functions, Route Handlers

The forbidden() function can be invoked in Server Components, Server Functions, and Route Handlers.

forbidden with Suspense streaming example

When forbidden() is called inside a Suspense boundary after streaming has started, the exception propagates to the nearest forbidden boundary, which renders in place of the streamed-in content even though the page shell has already been sent. However, because the check runs inside the Suspense boundary, the response has already begun streaming as a 200, and the status cannot change once streaming has started. To return a real 403 status, the check must run before the response streams, such as in a proxy file.

forbidden introduced in version 15.1.0

The forbidden() function was introduced in Next.js version 15.1.0.

forbidden function example: Server Action mutations

Example showing how to use forbidden() in a Server Action to restrict role updates: ```ts 'use server' import { verifySession } from '@/app/lib/dal' import { forbidden } from 'next/navigation' import db from '@/app/lib/db' export async function updateRole(formData: FormData) { const session = await verifySession() if (session.role !== 'admin') { forbidden() } // Perform the role update for authorized users // ... } ```

options.next.tags parameter

Set cache tags of a resource using next: { tags: ['collection'] }. Data can then be revalidated on-demand using revalidateTag(). The max length for a custom tag is 256 characters and the max tag items is 128.

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.

fetch() automatic memoization in Server Components

Fetch requests using GET with the same URL and options are automatically memoized during a server render pass. If you call the same fetch in multiple Server Components, layouts, pages, generateStaticParams, and generateViewport, Next.js executes it only once and shares the result. Memoization is separate from persistent caching: memoization lasts only for a single render pass, while cached responses persist across requests. Memoization does not apply in Route Handlers, since they are not part of the React component tree.

fetch() revalidate interaction with route default

If an individual fetch() request sets a revalidate number lower than the default revalidate of a route, the whole route revalidation interval will be decreased. If two fetch requests with the same URL in the same route have different revalidate values, the lower value will be used.

fetch() API overview

Next.js extends the Web fetch() API to allow each server request to set its own persistent caching and revalidation semantics. In the browser, the cache option indicates how a fetch request interacts with the browser's HTTP cache. In Next.js, the cache option indicates how a server-side fetch request interacts with the framework's persistent cache. You can call fetch with async and await directly within Server Components.

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() conflicting revalidate and cache options

Conflicting options such as { revalidate: 3600, cache: 'no-store' } are not allowed. Both will be ignored, and in development mode a warning will be printed to the terminal.

fetch() opt out of memoization with AbortController

To opt out of fetch memoization, pass an AbortController signal to fetch: const { signal } = new AbortController() fetch(url, { signal })

fetch() caching is opt-in

Caching is opt-in. Set cache: 'force-cache' to cache any request, including POST requests and requests that send authorization or cookie headers. Draft Mode bypasses the cache entirely (no read or write).

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.next.revalidate parameter values

The next.revalidate option sets the cache lifetime of a resource in seconds and accepts the following values: - false: Cache the resource indefinitely. Semantically equivalent to revalidate: Infinity. The HTTP cache may evict older resources over time. - 0: Prevent the resource from being cached. - number: Specify the resource should have a cache lifetime of at most n seconds.

HMR cache and fetch requests in development

Next.js caches fetch responses in Server Components across Hot Module Replacement (HMR) in local development for faster responses and to reduce costs for billed API calls. By default, the HMR cache applies to all fetch requests, including those with the default 'auto' and cache: 'no-store' option. This means uncached requests will not show fresh data between HMR refreshes. However, the cache will be cleared on navigation or full-page reloads.

Give your agent this brain