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

file-conventions

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

global-error.js file convention

global-error.jsx is used to handle errors in the root layout or template. It is located in the root app directory and must define its own <html> and <body> tags. It replaces the root layout or template when active. global-error must be a Client Component and does not support metadata exports.

reset() function in error.js

The reset() function clears the error state and re-renders the error boundary's children without re-fetching the contents. It should only be used if there is a specific reason to avoid re-fetching.

error.digest property

error.digest is an automatically generated hash of the error thrown. It can be used to match the corresponding error in server-side logs. For Server Component errors, the digest identifier can be used to match corresponding server-side logs.

error prop structure

The error prop is of type Error & { digest?: string }. In development, errors forwarded from Client Components show the original Error message. Errors forwarded from Server Components show a generic message with an identifier to prevent leaking sensitive details.

error.js component props

The error component receives two props: error and retry. The error prop is an instance of an Error object with an optional digest property. The retry prop is a function that attempts to recover by re-fetching and re-rendering the error boundary's children.

error.js scope and hierarchy

In the component hierarchy, error.js wraps loading.js, not-found.js, page.js, and nested layout.js files in a React error boundary. It does not wrap the layout.js or template.js above it in the same segment. To handle errors in the root layout, use global-error.js instead.

error.js file convention

error.js is a special file that handles unexpected runtime errors and displays fallback UI. It must be a Client Component (marked with 'use client'). It wraps a route segment and its nested children in a React Error Boundary.

Intercepting routes convention

Intercepting routes are defined using parentheses notation to match segments at different levels: (.) matches segments on the same level, (..) matches segments one level above, (..)(..) matches segments two levels above, and (...) matches segments from the root app directory.

Intercepting routes example use cases

Intercepting routes can be used for opening a photo in a modal from a feed while masking the URL, opening a login modal in a top navbar while having a dedicated /login page, or opening a shopping cart in a side modal.

Intercepting routes based on route segments not file system

The (..) convention for intercepting routes is based on route segments, not the file system. It does not consider @slot folders used in Parallel Routes when calculating segment levels.

Intercepting routes definition and behavior

Intercepting routes allow you to load a route from another part of your application within the current layout without the user switching to a different context. The route content displays while masking the browser URL. On soft navigation (client-side), the route is intercepted and overlaid. On hard navigation (direct URL access or page refresh), the entire route page renders instead of being intercepted.

instrumentation.js purpose

The instrumentation.js|ts file is used to integrate observability tools into an application to track performance and behavior and debug issues in production.

instrumentation.js version history

Version history: v15.0.0 introduced onRequestError and made instrumentation stable; v14.0.4 added Turbopack support for instrumentation; v13.2.0 introduced instrumentation as an experimental feature.

instrumentation.js runtime targeting example

Example of targeting specific runtime in instrumentation.js: export function register() { if (process.env.NEXT_RUNTIME === 'edge') { return require('./register.edge') } else { return require('./register.node') } } export function onRequestError() { if (process.env.NEXT_RUNTIME === 'edge') { return require('./on-request-error.edge') } else { return require('./on-request-error.node') } }

instrumentation.js runtime support

The instrumentation.js file works in both the Node.js and Edge runtime. The process.env.NEXT_RUNTIME environment variable can be used to target a specific runtime ('edge' or otherwise).

onRequestError context parameter structure

The context parameter passed to onRequestError has the following properties: routerKind (either 'Pages Router' or 'App Router'), routePath (string, route file path like /app/blog/[dynamic]), routeType (either 'render', 'route', 'action', or 'proxy'), renderSource (either 'react-server-components', 'react-server-components-payload', or 'server-rendering'), revalidateReason (either 'on-demand', 'stale', or undefined for normal requests), and renderType (either 'dynamic' or 'dynamic-resume' for PPR).

onRequestError request parameter structure

The request parameter passed to onRequestError has the following structure: path (string, resource path like /blog?name=foo), method (string, request method like GET or POST), and headers (object with string or string array values).

onRequestError parameters

The onRequestError function accepts three parameters: error (typed as unknown), request (with path, method, and headers properties), and context (with routerKind, routePath, routeType, renderSource, revalidateReason, and renderType properties). The error parameter must be narrowed before reading properties. The request object is read-only. The context object describes the router type and context in which the error occurred.

onRequestError function example

Example of an onRequestError function in instrumentation.ts: import { type Instrumentation } from 'next' export const onRequestError: Instrumentation.onRequestError = async ( err, request, context ) => { const message = err instanceof Error ? err.message : String(err) const digest = typeof err === 'object' && err !== null && 'digest' in err ? String(err.digest) : undefined await fetch('https://.../report-error', { method: 'POST', body: JSON.stringify({ message, digest, request, context, }), headers: { 'Content-Type': 'application/json', }, }) }

onRequestError error instance behavior

The error instance passed to onRequestError might not be the original error instance thrown, as it may be processed by React if encountered during Server Components rendering. The digest property on an error can be used to identify the actual error type.

onRequestError function in instrumentation.js

The onRequestError function is an optional export that tracks server errors to any custom observability provider. If running async tasks in onRequestError, they must be awaited. The onRequestError will be triggered when the Next.js server captures the error.

register function example

Example of a register function in instrumentation.ts: import { registerOTel } from '@vercel/otel' export function register() { registerOTel('next-app') }

register function in instrumentation.js

The register function is an optional export that is called once when a new Next.js server instance is initiated and must complete before the server is ready to handle requests. The register function can be an async function.

instrumentation-client error handling recommendation

Implement try-catch blocks around instrumentation code to ensure robust monitoring and prevent individual tracking failures from affecting other instrumentation features.

instrumentation-client polyfill anti-pattern

Avoid loading a polyfill with a conditional import() in instrumentation-client. The import is fire-and-forget, so the polyfill may be applied after hydration has already begun, which can be too late for components. Instead, use static imports and apply synchronously.

instrumentation-client polyfill static import example

Example showing the correct way to apply a polyfill before components run using static import: import ResizeObserverPolyfill from './lib/polyfills/resize-observer' if (!window.ResizeObserver) { window.ResizeObserver = ResizeObserverPolyfill }

instrumentation-client.js router transition start with event example

Example showing how to use onRouterTransitionStart with the event object (when experimental.instrumentationClientRouterTransitionEvents is enabled): import type { RouterTransitionStartEvent, RouterTransitionType } from 'next' export function onRouterTransitionStart( url: string, navigationType: RouterTransitionType, { id, timestamp, fromRoutes, prefetchIntent }: RouterTransitionStartEvent ) { console.log(id, timestamp, url, navigationType, fromRoutes, prefetchIntent) }

Analytics tracking example with instrumentation-client.ts

Example code showing how to initialize analytics and track navigation events: import { analytics } from './lib/analytics' analytics.init() export function onRouterTransitionStart(url: string, navigationType: string) { analytics.track('page_navigation', { url, type: navigationType, timestamp: Date.now(), }) }

Performance monitoring example with instrumentation-client.ts

Example code showing how to track Time to Interactive and navigation performance: const startTime = performance.now() const observer = new PerformanceObserver( (list: PerformanceObserverEntryList) => { for (const entry of list.getEntries()) { if (entry instanceof PerformanceNavigationTiming) { console.log('Time to Interactive:', entry.loadEventEnd - startTime) } } } ) observer.observe({ entryTypes: ['navigation'] }) export function onRouterTransitionStart(url: string) { performance.mark(`nav-start-${url}`) }

instrumentation-client async work not awaited

Asynchronous work started in instrumentation-client (a Promise, import(), or top-level await) is not awaited and may resolve after hydration has begun. Treat it as fire-and-forget. When something must be in place before components run, use synchronous patterns.

experimentalInstrumentationClientRouterTransitionEvents config option

Set experimental.instrumentationClientRouterTransitionEvents to true in next.config.ts to enable the third event argument in onRouterTransitionStart with transition metadata and source context.

instrumentation-client.js router transition start hook example

Example showing how to export onRouterTransitionStart: export function onRouterTransitionStart( url: string, navigationType: 'push' | 'replace' | 'traverse' ) { console.log(url, navigationType) }

instrumentation-client.js basic usage example

Example showing basic instrumentation setup: // Set up performance monitoring performance.mark('app-init') // Initialize analytics console.log('Analytics initialized') // Set up error tracking window.addEventListener('error', (event) => { // Send to your error tracking service reportError(event.error) })

onRouterTransitionStart event object properties

When experimental.instrumentationClientRouterTransitionEvents is enabled, the event object passed to onRouterTransitionStart includes: id (an opaque ID shared by events for this transition), timestamp (a framework-captured Unix timestamp in milliseconds), fromRoutes (route patterns visible before navigation, with the primary children route first followed by parallel slots in deterministic order), and prefetchIntent (for link navigations: 'full' for full prefetching, 'auto' for automatic prefetching, or 'none' for no prefetching; null for navigations with no associated link).

Error tracking example with instrumentation-client.ts

Example code showing how to initialize error tracking before React starts and add navigation breadcrumbs: import Monitor from './lib/monitoring' Monitor.initialize() export function onRouterTransitionStart(url: string) { Monitor.pushEvent({ message: `Navigation to ${url}`, category: 'navigation', }) }

instrumentation-client.js polyfill implementation pattern

To guarantee a polyfill is applied before components run, statically import it and apply it synchronously after feature detection. Because the import is static, the polyfill ships to every visitor. Avoid conditional import() or top-level await, as these are fire-and-forget and the polyfill may be applied after hydration has begun, which can be too late.

onRouterTransitionStart error isolation

Hook errors in onRouterTransitionStart are isolated and do not affect navigation or other hooks.

onRouterTransitionStart route pattern format

Route entries in fromRoutes use filesystem-style patterns, so a navigation away from /blog/hello may report /blog/[slug].

instrumentation-client performance warning threshold

Next.js monitors initialization time in development and will log warnings if instrumentation-client code takes longer than 16ms, which could impact smooth page loading.

onRouterTransitionStart export function signature

You can export onRouterTransitionStart to observe the start of App Router navigations. The function receives three parameters: url (string) - the URL being navigated to, navigationType ('push' | 'replace' | 'traverse') - the type of navigation, and an optional event object (when experimental.instrumentationClientRouterTransitionEvents is enabled).

instrumentation-client.js execution timing lifecycle

The instrumentation-client.js file executes at a specific point: after the HTML document is loaded, before React hydration begins, and before user interactions are possible. Only synchronous, top-level code is guaranteed to complete before hydration. Asynchronous work started here (a Promise, import(), or top-level await) is not awaited and may resolve after hydration has begun, so it is treated as fire-and-forget.

instrumentation-client.js purpose and capabilities

The instrumentation-client.js|ts file allows you to add monitoring, analytics code, and other side-effects that run before your application becomes interactive. It is useful for setting up performance tracking, error monitoring, polyfills, or any other client-side observability tools. Unlike server-side instrumentation, you do not need to export any specific functions and can write monitoring code directly in the file.

instrumentation-client.js file convention location

The instrumentation-client.js|ts file must be placed in the root of your application or inside a src folder.

MDX Components version history

MDX Components feature was added in Next.js version v13.1.2.

mdx-components customization for styles

The mdx-components.js or mdx-components.tsx file can be used to customize styles and components when using @next/mdx with App Router.

mdx-components.js example structure

Example of a basic mdx-components.js file: const components = {}; export function useMDXComponents() { return components; }

mdx-components.tsx example structure

Example of a basic mdx-components.tsx file: import type { MDXComponents } from 'mdx/types'; const components: MDXComponents = {}; export function useMDXComponents(): MDXComponents { return components; }

useMDXComponents export requirement

The mdx-components.js or mdx-components.tsx file must export a single function named useMDXComponents. This function does not accept any arguments and returns an MDXComponents object.

mdx-components file location

The mdx-components.tsx or mdx-components.js file must be placed in the root of the project, at the same level as the pages or app directory, or inside src if applicable.

mdx-components.js file requirement

The mdx-components.js or mdx-components.tsx file is required to use @next/mdx with App Router. Without this file, @next/mdx will not work.

middleware.js file convention deprecated in Next.js 16

The middleware.js file convention has been deprecated in Next.js 16 and renamed to proxy.js. All functionality remains the same; only the file and export names have changed.

Migrate middleware.js to proxy.js using codemod

You can automatically migrate from middleware.js to proxy.js by running the command: npx @next/codemod@canary middleware-to-proxy .

loading.js does not accept parameters

Loading UI components defined in loading.js do not accept any parameters.

loading.js is a Server Component by default

By default, loading.js is a Server Component but can also be used as a Client Component through the 'use client' directive.

loading.js Suspense boundary wrapping behavior

In the same folder, loading.js is nested inside layout.js and automatically wraps the page.js file and any children below in a <Suspense> boundary. In the component hierarchy, loading.js wraps not-found.js, page.js, and nested layout.js files in a <Suspense> boundary. It does not wrap the layout.js, template.js, or error.js in the same segment.

loading.js prefetch and navigation behavior

The fallback UI is prefetched, making navigation immediate unless prefetching hasn't completed. Navigation is interruptible, meaning changing routes does not need to wait for the content of the route to fully load before navigating to another route. Shared layouts remain interactive while new route segments load.

loading.js file convention purpose

The loading.js special file creates meaningful Loading UI using React Suspense. It shows an instant loading state from the server while the content of a route segment streams in. Once streaming is complete, the new content is automatically swapped in.

loading.js instant loading states

An instant loading state is fallback UI shown immediately upon navigation. You can prerender loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo or title. Create a loading state by adding a loading.js file inside a folder.

loading.js with uncached or runtime data in layout

If the layout accesses uncached or runtime data (e.g. cookies(), headers(), or uncached fetches), loading.js will not show a fallback for it. Without Cache Components, navigation blocks until the layout finishes rendering. With Cache Components, uncached or runtime data access in the layout must be explicitly wrapped in <Suspense>, otherwise Next.js guides you with a build-time error. The static shell streams first, and the uncached content fills in. To ensure instant navigation, move uncached data fetching from layout.js into page.js, or wrap the runtime data access in your layout in its own <Suspense> boundary.

loading.js SEO behavior for bots

For bots that only scrape static HTML and cannot execute JavaScript like a full browser (such as Twitterbot), Next.js resolves generateMetadata before streaming UI, and metadata is placed in the <head> of the initial HTML. Otherwise, streaming metadata may be used. Next.js automatically detects user agents to choose between blocking and streaming behavior. Since streaming is server-rendered, it does not impact SEO.

Give your agent this brain