# Nextjs > The Next.js team is committed to making Next.js accessible to all developers (and their end-users). By adding accessibility features to Next.js by default, we aim to make the Web more inclusive for ev --- # Source: https://nextjs.org/docs/architecture/accessibility.md # Accessibility @doc-version: 16.0.4 The Next.js team is committed to making Next.js accessible to all developers (and their end-users). By adding accessibility features to Next.js by default, we aim to make the Web more inclusive for everyone. ## Route Announcements When transitioning between pages rendered on the server (e.g. using the `` tag) screen readers and other assistive technology announce the page title when the page loads so that users understand that the page has changed. In addition to traditional page navigations, Next.js also supports client-side transitions for improved performance (using `next/link`). To ensure that client-side transitions are also announced to assistive technology, Next.js includes a route announcer by default. The Next.js route announcer looks for the page name to announce by first inspecting `document.title`, then the `

` element, and finally the URL pathname. For the most accessible user experience, ensure that each page in your application has a unique and descriptive title. ## Linting Next.js provides an [integrated ESLint experience](/docs/pages/api-reference/config/eslint.md) out of the box, including custom rules for Next.js. By default, Next.js includes `eslint-plugin-jsx-a11y` to help catch accessibility issues early, including warning on: * [aria-props](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/aria-props.md?rgh-link-date=2021-06-04T02%3A10%3A36Z) * [aria-proptypes](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/aria-proptypes.md?rgh-link-date=2021-06-04T02%3A10%3A36Z) * [aria-unsupported-elements](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/aria-unsupported-elements.md?rgh-link-date=2021-06-04T02%3A10%3A36Z) * [role-has-required-aria-props](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/role-has-required-aria-props.md?rgh-link-date=2021-06-04T02%3A10%3A36Z) * [role-supports-aria-props](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/role-supports-aria-props.md?rgh-link-date=2021-06-04T02%3A10%3A36Z) For example, this plugin helps ensure you add alt text to `img` tags, use correct `aria-*` attributes, use correct `role` attributes, and more. ## Accessibility Resources * [WebAIM WCAG checklist](https://webaim.org/standards/wcag/checklist) * [WCAG 2.2 Guidelines](https://www.w3.org/TR/WCAG22/) * [The A11y Project](https://www.a11yproject.com/) * Check [color contrast ratios](https://developer.mozilla.org/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) between foreground and background elements * Use [`prefers-reduced-motion`](https://web.dev/prefers-reduced-motion/) when working with animations --- # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/adapterPath.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/adapterPath.md # experimental.adapterPath @doc-version: 16.0.4 Next.js provides an experimental API that allows you to create custom adapters to hook into the build process. This is useful for deployment platforms or custom build integrations that need to modify the Next.js configuration or process the build output. ## Configuration To use an adapter, specify the path to your adapter module in `experimental.adapterPath`: ```js filename="next.config.js" /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { adapterPath: require.resolve('./my-adapter.js'), }, } module.exports = nextConfig ``` ## Creating an Adapter An adapter is a module that exports an object implementing the `NextAdapter` interface: ```typescript export interface NextAdapter { name: string modifyConfig?: ( config: NextConfigComplete, ctx: { phase: PHASE_TYPE } ) => Promise | NextConfigComplete onBuildComplete?: (ctx: { routes: { headers: Array redirects: Array rewrites: { beforeFiles: Array afterFiles: Array fallback: Array } dynamicRoutes: ReadonlyArray } outputs: AdapterOutputs projectDir: string repoRoot: string distDir: string config: NextConfigComplete nextVersion: string }) => Promise | void } ``` ### Basic Adapter Structure Here's a minimal adapter example: ```js filename="my-adapter.js" /** @type {import('next').NextAdapter} */ const adapter = { name: 'my-custom-adapter', async modifyConfig(config, { phase }) { // Modify the Next.js config based on the build phase if (phase === 'phase-production-build') { return { ...config, // Add your modifications } } return config }, async onBuildComplete({ routes, outputs, projectDir, repoRoot, distDir, config, nextVersion, }) { // Process the build output console.log('Build completed with', outputs.pages.length, 'pages') // Access different output types for (const page of outputs.pages) { console.log('Page:', page.pathname, 'at', page.filePath) } for (const apiRoute of outputs.pagesApi) { console.log('API Route:', apiRoute.pathname, 'at', apiRoute.filePath) } for (const appPage of outputs.appPages) { console.log('App Page:', appPage.pathname, 'at', appPage.filePath) } for (const prerender of outputs.prerenders) { console.log('Prerendered:', prerender.pathname) } }, } module.exports = adapter ``` ## API Reference ### `modifyConfig(config, context)` Called for any CLI command that loads the next.config to allow modification of the configuration. **Parameters:** * `config`: The complete Next.js configuration object * `context.phase`: The current build phase (see [phases](/docs/app/api-reference/config/next-config-js.md#phase)) **Returns:** The modified configuration object (can be async) ### `onBuildComplete(context)` Called after the build process completes with detailed information about routes and outputs. **Parameters:** * `routes`: Object containing route manifests for headers, redirects, rewrites, and dynamic routes * `routes.headers`: Array of header route objects with `source`, `sourceRegex`, `headers`, `has`, `missing`, and optional `priority` fields * `routes.redirects`: Array of redirect route objects with `source`, `sourceRegex`, `destination`, `statusCode`, `has`, `missing`, and optional `priority` fields * `routes.rewrites`: Object with `beforeFiles`, `afterFiles`, and `fallback` arrays, each containing rewrite route objects with `source`, `sourceRegex`, `destination`, `has`, and `missing` fields * `routes.dynamicRoutes`: Array of dynamic route objects with `source`, `sourceRegex`, `destination`, `has`, and `missing` fields * `outputs`: Detailed information about all build outputs organized by type * `projectDir`: Absolute path to the Next.js project directory * `repoRoot`: Absolute path to the detected repository root * `distDir`: Absolute path to the build output directory * `config`: The final Next.js configuration (with `modifyConfig` applied) * `nextVersion`: Version of Next.js being used * `buildId`: Unique identifier for the current build ## Output Types The `outputs` object contains arrays of different output types: ### Pages (`outputs.pages`) React pages from the `pages/` directory: ```typescript { type: 'PAGES' id: string // Route identifier filePath: string // Path to the built file pathname: string // URL pathname sourcePage: string // Original source file path in pages/ directory runtime: 'nodejs' | 'edge' assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) config: { maxDuration?: number preferredRegion?: string | string[] env?: Record // Environment variables (edge runtime only) } } ``` ### API Routes (`outputs.pagesApi`) API routes from `pages/api/`: ```typescript { type: 'PAGES_API' id: string filePath: string pathname: string sourcePage: string // Original relative source file path runtime: 'nodejs' | 'edge' assets: Record wasmAssets?: Record config: { maxDuration?: number preferredRegion?: string | string[] env?: Record } } ``` ### App Pages (`outputs.appPages`) React pages from the `app/` directory with `page.{js,ts,jsx,tsx}`: ```typescript { type: 'APP_PAGE' id: string filePath: string pathname: string // Includes .rsc suffix for RSC routes sourcePage: string // Original relative source file path runtime: 'nodejs' | 'edge' assets: Record wasmAssets?: Record config: { maxDuration?: number preferredRegion?: string | string[] env?: Record } } ``` ### App Routes (`outputs.appRoutes`) API and metadata routes from `app/` with `route.{js,ts,jsx,tsx}`: ```typescript { type: 'APP_ROUTE' id: string filePath: string pathname: string sourcePage: string runtime: 'nodejs' | 'edge' assets: Record wasmAssets?: Record config: { maxDuration?: number preferredRegion?: string | string[] env?: Record } } ``` ### Prerenders (`outputs.prerenders`) ISR-enabled routes and static prerenders: ```typescript { type: 'PRERENDER' id: string pathname: string parentOutputId: string // ID of the source page/route groupId: number // Revalidation group identifier (prerenders with same groupId revalidate together) pprChain?: { headers: Record // PPR chain headers (e.g., 'x-nextjs-resume': '1') } parentFallbackMode?: 'blocking' | false | null // Fallback mode from getStaticPaths fallback?: { filePath: string initialStatus?: number initialHeaders?: Record initialExpiration?: number initialRevalidate?: number postponedState?: string // PPR postponed state } config: { allowQuery?: string[] // Allowed query parameters allowHeader?: string[] // Allowed headers for ISR bypassFor?: RouteHas[] // Cache bypass conditions renderingMode?: RenderingMode bypassToken?: string } } ``` ### Static Files (`outputs.staticFiles`) Static assets and auto-statically optimized pages: ```typescript { type: 'STATIC_FILE' id: string filePath: string pathname: string } ``` ### Middleware (`outputs.middleware`) Middleware function (if present): ```typescript { type: 'MIDDLEWARE' id: string filePath: string pathname: string // Always '/_middleware' sourcePage: string // Always 'middleware' runtime: 'nodejs' | 'edge' assets: Record wasmAssets?: Record config: { maxDuration?: number preferredRegion?: string | string[] env?: Record matchers?: Array<{ source: string sourceRegex: string has: RouteHas[] | undefined missing: RouteHas[] | undefined }> } } ``` ## Routes Information The `routes` object in `onBuildComplete` provides complete routing information with processed patterns ready for deployment: ### Headers Each header route includes: * `source`: Original route pattern (e.g., `/about`) * `sourceRegex`: Compiled regex for matching requests * `headers`: Key-value pairs of headers to apply * `has`: Optional conditions that must be met * `missing`: Optional conditions that must not be met * `priority`: Optional flag for internal routes ### Redirects Each redirect route includes: * `source`: Original route pattern * `sourceRegex`: Compiled regex for matching * `destination`: Target URL (can include captured groups) * `statusCode`: HTTP status code (301, 302, 307, 308) * `has`: Optional positive conditions * `missing`: Optional negative conditions * `priority`: Optional flag for internal routes ### Rewrites Rewrites are categorized into three phases: * `beforeFiles`: Checked before filesystem (including pages and public files) * `afterFiles`: Checked after pages/public files but before dynamic routes * `fallback`: Checked after all other routes Each rewrite includes `source`, `sourceRegex`, `destination`, `has`, and `missing`. ### Dynamic Routes Generated from dynamic route segments (e.g., `[slug]`, `[...path]`). Each includes: * `source`: Route pattern * `sourceRegex`: Compiled regex with named capture groups * `destination`: Internal destination with parameter substitution * `has`: Optional positive conditions * `missing`: Optional negative conditions ## Use Cases Common use cases for adapters include: * **Deployment Platform Integration**: Automatically configure build outputs for specific hosting platforms * **Asset Processing**: Transform or optimize build outputs * **Monitoring Integration**: Collect build metrics and route information * **Custom Bundling**: Package outputs in platform-specific formats * **Build Validation**: Ensure outputs meet specific requirements * **Route Generation**: Use processed route information to generate platform-specific routing configs --- # Source: https://nextjs.org/docs/app/api-reference/functions/after.md # after @doc-version: 16.0.4 `after` allows you to schedule work to be executed after a response (or prerender) is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics. It can be used in [Server Components](/docs/app/getting-started/server-and-client-components.md) (including [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata.md)), [Server Actions](/docs/app/getting-started/updating-data.md), [Route Handlers](/docs/app/api-reference/file-conventions/route.md), and [Proxy](/docs/app/api-reference/file-conventions/proxy.md). The function accepts a callback that will be executed after the response (or prerender) is finished: ```tsx filename="app/layout.tsx" switcher import { after } from 'next/server' // Custom logging function import { log } from '@/app/utils' export default function Layout({ children }: { children: React.ReactNode }) { after(() => { // Execute after the layout is rendered and sent to the user log() }) return <>{children} } ``` ```jsx filename="app/layout.jsx" switcher import { after } from 'next/server' // Custom logging function import { log } from '@/app/utils' export default function Layout({ children }) { after(() => { // Execute after the layout is rendered and sent to the user log() }) return <>{children} } ``` > **Good to know:** `after` is not a [Dynamic API](/docs/app/guides/caching.md#dynamic-rendering) and calling it does not cause a route to become dynamic. If it's used within a static page, the callback will execute at build time, or whenever a page is revalidated. ## Reference ### Parameters * A callback function which will be executed after the response (or prerender) is finished. ### Duration `after` will run for the platform's default or configured max duration of your route. If your platform supports it, you can configure the timeout limit using the [`maxDuration`](/docs/app/api-reference/file-conventions/route-segment-config.md#maxduration) route segment config. ## Good to know * `after` will be executed even if the response didn't complete successfully. Including when an error is thrown or when `notFound` or `redirect` is called. * You can use React `cache` to deduplicate functions called inside `after`. * `after` can be nested inside other `after` calls, for example, you can create utility functions that wrap `after` calls to add additional functionality. ## Examples ### With request APIs You can use request APIs such as [`cookies`](/docs/app/api-reference/functions/cookies.md) and [`headers`](/docs/app/api-reference/functions/headers.md) inside `after` in [Server Actions](/docs/app/getting-started/updating-data.md) and [Route Handlers](/docs/app/api-reference/file-conventions/route.md). This is useful for logging activity after a mutation. For example: ```ts filename="app/api/route.ts" highlight={2,7-9} switcher import { after } from 'next/server' import { cookies, headers } from 'next/headers' import { logUserAction } from '@/app/utils' export async function POST(request: Request) { // Perform mutation // ... // Log user activity for analytics after(async () => { const userAgent = (await headers().get('user-agent')) || 'unknown' const sessionCookie = (await cookies().get('session-id'))?.value || 'anonymous' logUserAction({ sessionCookie, userAgent }) }) return new Response(JSON.stringify({ status: 'success' }), { status: 200, headers: { 'Content-Type': 'application/json' }, }) } ``` ```js filename="app/api/route.js" highlight={2,7-9} switcher import { after } from 'next/server' import { cookies, headers } from 'next/headers' import { logUserAction } from '@/app/utils' export async function POST(request) { // Perform mutation // ... // Log user activity for analytics after(async () => { const userAgent = (await headers().get('user-agent')) || 'unknown' const sessionCookie = (await cookies().get('session-id'))?.value || 'anonymous' logUserAction({ sessionCookie, userAgent }) }) return new Response(JSON.stringify({ status: 'success' }), { status: 200, headers: { 'Content-Type': 'application/json' }, }) } ``` However, you cannot use these request APIs inside `after` in [Server Components](/docs/app/getting-started/server-and-client-components.md). This is because Next.js needs to know which part of the tree access the request APIs to support [Cache Components](/docs/app/getting-started/cache-components.md), but `after` runs after React's rendering lifecycle. ## Platform Support | Deployment Option | Supported | | ------------------------------------------------------------------- | ----------------- | | [Node.js server](/docs/app/getting-started/deploying.md#nodejs-server) | Yes | | [Docker container](/docs/app/getting-started/deploying.md#docker) | Yes | | [Static export](/docs/app/getting-started/deploying.md#static-export) | No | | [Adapters](/docs/app/getting-started/deploying.md#adapters) | Platform-specific | Learn how to [configure `after`](/docs/app/guides/self-hosting.md#after) when self-hosting Next.js.
Reference: supporting `after` for serverless platforms Using `after` in a serverless context requires waiting for asynchronous tasks to finish after the response has been sent. In Next.js and Vercel, this is achieved using a primitive called `waitUntil(promise)`, which extends the lifetime of a serverless invocation until all promises passed to [`waitUntil`](https://vercel.com/docs/functions/functions-api-reference#waituntil) have settled. If you want your users to be able to run `after`, you will have to provide your implementation of `waitUntil` that behaves in an analogous way. When `after` is called, Next.js will access `waitUntil` like this: ```jsx const RequestContext = globalThis[Symbol.for('@next/request-context')] const contextValue = RequestContext?.get() const waitUntil = contextValue?.waitUntil ``` Which means that `globalThis[Symbol.for('@next/request-context')]` is expected to contain an object like this: ```tsx type NextRequestContext = { get(): NextRequestContextValue | undefined } type NextRequestContextValue = { waitUntil?: (promise: Promise) => void } ``` Here is an example of the implementation. ```tsx import { AsyncLocalStorage } from 'node:async_hooks' const RequestContextStorage = new AsyncLocalStorage() // Define and inject the accessor that next.js will use const RequestContext: NextRequestContext = { get() { return RequestContextStorage.getStore() }, } globalThis[Symbol.for('@next/request-context')] = RequestContext const handler = (req, res) => { const contextValue = { waitUntil: YOUR_WAITUNTIL } // Provide the value return RequestContextStorage.run(contextValue, () => nextJsHandler(req, res)) } ```
## Version History | Version History | Description | | --------------- | ---------------------------- | | `v15.1.0` | `after` became stable. | | `v15.0.0-rc` | `unstable_after` introduced. | --- # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/allowedDevOrigins.md # Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins.md # allowedDevOrigins @doc-version: 16.0.4 Next.js does not automatically block cross-origin requests during development, but will block by default in a future major version of Next.js to prevent unauthorized requesting of internal assets/endpoints that are available in development mode. To configure a Next.js application to allow requests from origins other than the hostname the server was initialized with (`localhost` by default) you can use the `allowedDevOrigins` config option. `allowedDevOrigins` allows you to set additional origins that can be used in development mode. For example, to use `local-origin.dev` instead of only `localhost`, open `next.config.js` and add the `allowedDevOrigins` config: ```js filename="next.config.js" module.exports = { allowedDevOrigins: ['local-origin.dev', '*.local-origin.dev'], } ``` --- # Source: https://nextjs.org/docs/pages/guides/analytics.md # Source: https://nextjs.org/docs/app/guides/analytics.md # Source: https://nextjs.org/docs/pages/guides/analytics.md # Source: https://nextjs.org/docs/app/guides/analytics.md # Source: https://nextjs.org/docs/pages/guides/analytics.md # Source: https://nextjs.org/docs/app/guides/analytics.md # Source: https://nextjs.org/docs/pages/guides/analytics.md # Source: https://nextjs.org/docs/app/guides/analytics.md # Source: https://nextjs.org/docs/pages/guides/analytics.md # Source: https://nextjs.org/docs/app/guides/analytics.md # How to add analytics to your Next.js application @doc-version: 16.0.4 Next.js has built-in support for measuring and reporting performance metrics. You can either use the [`useReportWebVitals`](/docs/app/api-reference/functions/use-report-web-vitals.md) hook to manage reporting yourself, or alternatively, Vercel provides a [managed service](https://vercel.com/analytics?utm_source=next-site\&utm_medium=docs\&utm_campaign=next-website) to automatically collect and visualize metrics for you. ## Client Instrumentation For more advanced analytics and monitoring needs, Next.js provides a `instrumentation-client.js|ts` file that runs before your application's frontend code starts executing. This is ideal for setting up global analytics, error tracking, or performance monitoring tools. To use it, create an `instrumentation-client.js` or `instrumentation-client.ts` file in your application's root directory: ```js filename="instrumentation-client.js" // Initialize analytics before the app starts console.log('Analytics initialized') // Set up global error tracking window.addEventListener('error', (event) => { // Send to your error tracking service reportError(event.error) }) ``` ## Build Your Own ```jsx filename="app/_components/web-vitals.js" 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { console.log(metric) }) } ``` ```jsx filename="app/layout.js" import { WebVitals } from './_components/web-vitals' export default function Layout({ children }) { return ( {children} ) } ``` > Since the `useReportWebVitals` hook requires the `'use client'` directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the `WebVitals` component. View the [API Reference](/docs/app/api-reference/functions/use-report-web-vitals.md) for more information. ## Web Vitals [Web Vitals](https://web.dev/vitals/) are a set of useful metrics that aim to capture the user experience of a web page. The following web vitals are all included: * [Time to First Byte](https://developer.mozilla.org/docs/Glossary/Time_to_first_byte) (TTFB) * [First Contentful Paint](https://developer.mozilla.org/docs/Glossary/First_contentful_paint) (FCP) * [Largest Contentful Paint](https://web.dev/lcp/) (LCP) * [First Input Delay](https://web.dev/fid/) (FID) * [Cumulative Layout Shift](https://web.dev/cls/) (CLS) * [Interaction to Next Paint](https://web.dev/inp/) (INP) You can handle all the results of these metrics using the `name` property. ```tsx filename="app/_components/web-vitals.tsx" switcher 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { switch (metric.name) { case 'FCP': { // handle FCP results } case 'LCP': { // handle LCP results } // ... } }) } ``` ```jsx filename="app/_components/web-vitals.js" switcher 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { switch (metric.name) { case 'FCP': { // handle FCP results } case 'LCP': { // handle LCP results } // ... } }) } ``` ## Sending results to external systems You can send results to any endpoint to measure and track real user performance on your site. For example: ```js useReportWebVitals((metric) => { const body = JSON.stringify(metric) const url = 'https://example.com/analytics' // Use `navigator.sendBeacon()` if available, falling back to `fetch()`. if (navigator.sendBeacon) { navigator.sendBeacon(url, body) } else { fetch(url, { body, method: 'POST', keepalive: true }) } }) ``` > **Good to know**: If you use [Google Analytics](https://analytics.google.com/analytics/web/), using the > `id` value can allow you to construct metric distributions manually (to calculate percentiles, > etc.) > ```js > useReportWebVitals((metric) => { > // Use `window.gtag` if you initialized Google Analytics as this example: > // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics > window.gtag('event', metric.name, { > value: Math.round( > metric.name === 'CLS' ? metric.value * 1000 : metric.value > ), // values must be integers > event_label: metric.id, // id unique to current page load > non_interaction: true, // avoids affecting bounce rate. > }) > }) > ``` > > Read more about [sending results to Google Analytics](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics). --- # Source: https://nextjs.org/docs/pages/api-reference.md # Source: https://nextjs.org/docs/app/api-reference.md # Source: https://nextjs.org/docs/pages/api-reference.md # Source: https://nextjs.org/docs/app/api-reference.md # Source: https://nextjs.org/docs/pages/api-reference.md # Source: https://nextjs.org/docs/app/api-reference.md # Source: https://nextjs.org/docs/pages/api-reference.md # Source: https://nextjs.org/docs/app/api-reference.md # Source: https://nextjs.org/docs/pages/api-reference.md # Source: https://nextjs.org/docs/app/api-reference.md # API Reference @doc-version: 16.0.4 - [Directives](/docs/app/api-reference/directives.md) - Directives are used to modify the behavior of your Next.js application. - [Components](/docs/app/api-reference/components.md) - API Reference for Next.js built-in components. - [File-system conventions](/docs/app/api-reference/file-conventions.md) - API Reference for Next.js file-system conventions. - [Functions](/docs/app/api-reference/functions.md) - API Reference for Next.js Functions and Hooks. - [Configuration](/docs/app/api-reference/config.md) - Learn how to configure Next.js applications. - [CLI](/docs/app/api-reference/cli.md) - API Reference for the Next.js Command Line Interface (CLI) tools. - [Edge Runtime](/docs/app/api-reference/edge.md) - API Reference for the Edge Runtime. - [Turbopack](/docs/app/api-reference/turbopack.md) - Turbopack is an incremental bundler optimized for JavaScript and TypeScript, written in Rust, and built into Next.js. --- # Source: https://nextjs.org/docs/pages/building-your-application/routing/api-routes.md # API Routes
Examples * [API Routes Request Helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-proxy) * [API Routes with GraphQL](https://github.com/vercel/next.js/tree/canary/examples/api-routes-graphql) * [API Routes with REST](https://github.com/vercel/next.js/tree/canary/examples/api-routes-rest) * [API Routes with CORS](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors)
> **Good to know**: If you are using the App Router, you can use [Server Components](/docs/app/getting-started/server-and-client-components.md) or [Route Handlers](/docs/app/api-reference/file-conventions/route.md) instead of API Routes. API routes provide a solution to build a **public API** with Next.js. Any file inside the folder `pages/api` is mapped to `/api/*` and will be treated as an API endpoint instead of a `page`. They are server-side only bundles and won't increase your client-side bundle size. For example, the following API route returns a JSON response with a status code of `200`: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' type ResponseData = { message: string } export default function handler( req: NextApiRequest, res: NextApiResponse ) { res.status(200).json({ message: 'Hello from Next.js!' }) } ``` ```js filename="pages/api/hello.js" switcher export default function handler(req, res) { res.status(200).json({ message: 'Hello from Next.js!' }) } ``` > **Good to know**: > > * API Routes [do not specify CORS headers](https://developer.mozilla.org/docs/Web/HTTP/CORS), meaning they are **same-origin only** by default. You can customize such behavior by wrapping the request handler with the [CORS request helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors). * API Routes can't be used with [static exports](/docs/pages/guides/static-exports.md). However, [Route Handlers](/docs/app/api-reference/file-conventions/route.md) in the App Router can. > * API Routes will be affected by [`pageExtensions` configuration](/docs/pages/api-reference/config/next-config-js/pageExtensions.md) in `next.config.js`. ## Parameters ```tsx export default function handler(req: NextApiRequest, res: NextApiResponse) { // ... } ``` * `req`: An instance of [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage) * `res`: An instance of [http.ServerResponse](https://nodejs.org/api/http.html#class-httpserverresponse) ## HTTP Methods To handle different HTTP methods in an API route, you can use `req.method` in your request handler, like so: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'POST') { // Process a POST request } else { // Handle any other HTTP method } } ``` ```js filename="pages/api/hello.js" switcher export default function handler(req, res) { if (req.method === 'POST') { // Process a POST request } else { // Handle any other HTTP method } } ``` ## Request Helpers API Routes provide built-in request helpers which parse the incoming request (`req`): * `req.cookies` - An object containing the cookies sent by the request. Defaults to `{}` * `req.query` - An object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}` * `req.body` - An object containing the body parsed by `content-type`, or `null` if no body was sent ### Custom config Every API Route can export a `config` object to change the default configuration, which is the following: ```js export const config = { api: { bodyParser: { sizeLimit: '1mb', }, }, // Specifies the maximum allowed duration for this function to execute (in seconds) maxDuration: 5, } ``` `bodyParser` is automatically enabled. If you want to consume the body as a `Stream` or with [`raw-body`](https://www.npmjs.com/package/raw-body), you can set this to `false`. One use case for disabling the automatic `bodyParsing` is to allow you to verify the raw body of a **webhook** request, for example [from GitHub](https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github). ```js export const config = { api: { bodyParser: false, }, } ``` `bodyParser.sizeLimit` is the maximum size allowed for the parsed body, in any format supported by [bytes](https://github.com/visionmedia/bytes.js), like so: ```js export const config = { api: { bodyParser: { sizeLimit: '500kb', }, }, } ``` `externalResolver` is an explicit flag that tells the server that this route is being handled by an external resolver like *express* or *connect*. Enabling this option disables warnings for unresolved requests. ```js export const config = { api: { externalResolver: true, }, } ``` `responseLimit` is automatically enabled, warning when an API Routes' response body is over 4MB. If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to `false`. ```js export const config = { api: { responseLimit: false, }, } ``` `responseLimit` can also take the number of bytes or any string format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. This value will be the maximum response size before a warning is displayed. Default is 4MB. (see above) ```js export const config = { api: { responseLimit: '8mb', }, } ``` ## Response Helpers The [Server Response object](https://nodejs.org/api/http.html#http_class_http_serverresponse), (often abbreviated as `res`) includes a set of Express.js-like helper methods to improve the developer experience and increase the speed of creating new API endpoints. The included helpers are: * `res.status(code)` - A function to set the status code. `code` must be a valid [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) * `res.json(body)` - Sends a JSON response. `body` must be a [serializable object](https://developer.mozilla.org/docs/Glossary/Serialization) * `res.send(body)` - Sends the HTTP response. `body` can be a `string`, an `object` or a `Buffer` * `res.redirect([status,] path)` - Redirects to a specified path or URL. `status` must be a valid [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). If not specified, `status` defaults to "307" "Temporary redirect". * `res.revalidate(urlPath)` - [Revalidate a page on demand](/docs/pages/guides/incremental-static-regeneration.md#on-demand-revalidation-with-revalidatepath) using `getStaticProps`. `urlPath` must be a `string`. ### Setting the status code of a response When sending a response back to the client, you can set the status code of the response. The following example sets the status code of the response to `200` (`OK`) and returns a `message` property with the value of `Hello from Next.js!` as a JSON response: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' type ResponseData = { message: string } export default function handler( req: NextApiRequest, res: NextApiResponse ) { res.status(200).json({ message: 'Hello from Next.js!' }) } ``` ```js filename="pages/api/hello.js" switcher export default function handler(req, res) { res.status(200).json({ message: 'Hello from Next.js!' }) } ``` ### Sending a JSON response When sending a response back to the client you can send a JSON response, this must be a [serializable object](https://developer.mozilla.org/docs/Glossary/Serialization). In a real world application you might want to let the client know the status of the request depending on the result of the requested endpoint. The following example sends a JSON response with the status code `200` (`OK`) and the result of the async operation. It's contained in a try catch block to handle any errors that may occur, with the appropriate status code and error message caught and sent back to the client: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { try { const result = await someAsyncOperation() res.status(200).json({ result }) } catch (err) { res.status(500).json({ error: 'failed to load data' }) } } ``` ```js filename="pages/api/hello.js" switcher export default async function handler(req, res) { try { const result = await someAsyncOperation() res.status(200).json({ result }) } catch (err) { res.status(500).json({ error: 'failed to load data' }) } } ``` ### Sending a HTTP response Sending an HTTP response works the same way as when sending a JSON response. The only difference is that the response body can be a `string`, an `object` or a `Buffer`. The following example sends a HTTP response with the status code `200` (`OK`) and the result of the async operation. ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { try { const result = await someAsyncOperation() res.status(200).send({ result }) } catch (err) { res.status(500).send({ error: 'failed to fetch data' }) } } ``` ```js filename="pages/api/hello.js" switcher export default async function handler(req, res) { try { const result = await someAsyncOperation() res.status(200).send({ result }) } catch (err) { res.status(500).send({ error: 'failed to fetch data' }) } } ``` ### Redirects to a specified path or URL Taking a form as an example, you may want to redirect your client to a specified path or URL once they have submitted the form. The following example redirects the client to the `/` path if the form is successfully submitted: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { name, message } = req.body try { await handleFormInputAsync({ name, message }) res.redirect(307, '/') } catch (err) { res.status(500).send({ error: 'Failed to fetch data' }) } } ``` ```js filename="pages/api/hello.js" switcher export default async function handler(req, res) { const { name, message } = req.body try { await handleFormInputAsync({ name, message }) res.redirect(307, '/') } catch (err) { res.status(500).send({ error: 'failed to fetch data' }) } } ``` ### Adding TypeScript types You can make your API Routes more type-safe by importing the `NextApiRequest` and `NextApiResponse` types from `next`, in addition to those, you can also type your response data: ```ts import type { NextApiRequest, NextApiResponse } from 'next' type ResponseData = { message: string } export default function handler( req: NextApiRequest, res: NextApiResponse ) { res.status(200).json({ message: 'Hello from Next.js!' }) } ``` > **Good to know**: The body of `NextApiRequest` is `any` because the client may include any payload. You should validate the type/shape of the body at runtime before using it. ## Dynamic API Routes API Routes support [dynamic routes](/docs/pages/building-your-application/routing/dynamic-routes.md), and follow the same file naming rules used for `pages/`. ```ts filename="pages/api/post/[pid].ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { const { pid } = req.query res.end(`Post: ${pid}`) } ``` ```js filename="pages/api/post/[pid].js" switcher export default function handler(req, res) { const { pid } = req.query res.end(`Post: ${pid}`) } ``` Now, a request to `/api/post/abc` will respond with the text: `Post: abc`. ### Catch all API routes API Routes can be extended to catch all paths by adding three dots (`...`) inside the brackets. For example: * `pages/api/post/[...slug].js` matches `/api/post/a`, but also `/api/post/a/b`, `/api/post/a/b/c` and so on. > **Good to know**: You can use names other than `slug`, such as: `[...param]` Matched parameters will be sent as a query parameter (`slug` in the example) to the page, and it will always be an array, so, the path `/api/post/a` will have the following `query` object: ```json { "slug": ["a"] } ``` And in the case of `/api/post/a/b`, and any other matching path, new parameters will be added to the array, like so: ```json { "slug": ["a", "b"] } ``` For example: ```ts filename="pages/api/post/[...slug].ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { const { slug } = req.query res.end(`Post: ${slug.join(', ')}`) } ``` ```js filename="pages/api/post/[...slug].js" switcher export default function handler(req, res) { const { slug } = req.query res.end(`Post: ${slug.join(', ')}`) } ``` Now, a request to `/api/post/a/b/c` will respond with the text: `Post: a, b, c`. ### Optional catch all API routes Catch all routes can be made optional by including the parameter in double brackets (`[[...slug]]`). For example, `pages/api/post/[[...slug]].js` will match `/api/post`, `/api/post/a`, `/api/post/a/b`, and so on. The main difference between catch all and optional catch all routes is that with optional, the route without the parameter is also matched (`/api/post` in the example above). The `query` objects are as follows: ```json { } // GET `/api/post` (empty object) { "slug": ["a"] } // `GET /api/post/a` (single-element array) { "slug": ["a", "b"] } // `GET /api/post/a/b` (multi-element array) ``` ### Caveats * Predefined API routes take precedence over dynamic API routes, and dynamic API routes over catch all API routes. Take a look at the following examples: * `pages/api/post/create.js` - Will match `/api/post/create` * `pages/api/post/[pid].js` - Will match `/api/post/1`, `/api/post/abc`, etc. But not `/api/post/create` * `pages/api/post/[...slug].js` - Will match `/api/post/1/2`, `/api/post/a/b/c`, etc. But not `/api/post/create`, `/api/post/abc` ## Streaming responses While the Pages Router does support streaming responses with API Routes, we recommend incrementally adopting the App Router and using [Route Handlers](/docs/app/api-reference/file-conventions/route.md) if you are on Next.js 14+. Here's how you can stream a response from an API Route with `writeHead`: ```ts filename="pages/api/hello.ts" switcher import { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', }) let i = 0 while (i < 10) { res.write(`data: ${i}\n\n`) i++ await new Promise((resolve) => setTimeout(resolve, 1000)) } res.end() } ``` ```js filename="pages/api/hello.js" switcher export default async function handler(req, res) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', }) let i = 0 while (i < 10) { res.write(`data: ${i}\n\n`) i++ await new Promise((resolve) => setTimeout(resolve, 1000)) } res.end() } ``` --- # Source: https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons.md # favicon, icon, and apple-icon @doc-version: 16.0.4 The `favicon`, `icon`, or `apple-icon` file conventions allow you to set icons for your application. They are useful for adding app icons that appear in places like web browser tabs, phone home screens, and search engine results. There are two ways to set app icons: * [Using image files (.ico, .jpg, .png)](#image-files-ico-jpg-png) * [Using code to generate an icon (.js, .ts, .tsx)](#generate-icons-using-code-js-ts-tsx) ## Image files (.ico, .jpg, .png) Use an image file to set an app icon by placing a `favicon`, `icon`, or `apple-icon` image file within your `/app` directory. The `favicon` image can only be located in the top level of `app/`. Next.js will evaluate the file and automatically add the appropriate tags to your app's `` element. | File convention | Supported file types | Valid locations | | --------------------------- | --------------------------------------- | --------------- | | [`favicon`](#favicon) | `.ico` | `app/` | | [`icon`](#icon) | `.ico`, `.jpg`, `.jpeg`, `.png`, `.svg` | `app/**/*` | | [`apple-icon`](#apple-icon) | `.jpg`, `.jpeg`, `.png` | `app/**/*` | ### `favicon` Add a `favicon.ico` image file to the root `/app` route segment. ```html filename=" output" ``` ### `icon` Add an `icon.(ico|jpg|jpeg|png|svg)` image file. ```html filename=" output" ``` ### `apple-icon` Add an `apple-icon.(jpg|jpeg|png)` image file. ```html filename=" output" ``` > **Good to know**: > > * You can set multiple icons by adding a number suffix to the file name. For example, `icon1.png`, `icon2.png`, etc. Numbered files will sort lexically. > * Favicons can only be set in the root `/app` segment. If you need more granularity, you can use [`icon`](#icon). > * The appropriate `` tags and attributes such as `rel`, `href`, `type`, and `sizes` are determined by the icon type and metadata of the evaluated file. > * For example, a 32 by 32px `.png` file will have `type="image/png"` and `sizes="32x32"` attributes. > * `sizes="any"` is added to icons when the extension is `.svg` or the image size of the file is not determined. More details in this [favicon handbook](https://evilmartians.com/chronicles/how-to-favicon-in-2021-six-files-that-fit-most-needs). ## Generate icons using code (.js, .ts, .tsx) In addition to using [literal image files](#image-files-ico-jpg-png), you can programmatically **generate** icons using code. Generate an app icon by creating an `icon` or `apple-icon` route that default exports a function. | File convention | Supported file types | | --------------- | -------------------- | | `icon` | `.js`, `.ts`, `.tsx` | | `apple-icon` | `.js`, `.ts`, `.tsx` | The easiest way to generate an icon is to use the [`ImageResponse`](/docs/app/api-reference/functions/image-response.md) API from `next/og`. ```tsx filename="app/icon.tsx" switcher import { ImageResponse } from 'next/og' // Image metadata export const size = { width: 32, height: 32, } export const contentType = 'image/png' // Image generation export default function Icon() { return new ImageResponse( ( // ImageResponse JSX element
A
), // ImageResponse options { // For convenience, we can re-use the exported icons size metadata // config to also set the ImageResponse's width and height. ...size, } ) } ``` ```jsx filename="app/icon.js" switcher import { ImageResponse } from 'next/og' // Image metadata export const size = { width: 32, height: 32, } export const contentType = 'image/png' // Image generation export default function Icon() { return new ImageResponse( ( // ImageResponse JSX element
A
), // ImageResponse options { // For convenience, we can re-use the exported icons size metadata // config to also set the ImageResponse's width and height. ...size, } ) } ``` ```html filename=" output" ``` > **Good to know**: > > * By default, generated icons are [**statically optimized**](/docs/app/guides/caching.md#static-rendering) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/guides/caching.md#dynamic-rendering) or uncached data. > * You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata.md). > * You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead. > * App icons are special Route Handlers that are cached by default unless they use a [Dynamic API](/docs/app/guides/caching.md#dynamic-apis) or [dynamic config](/docs/app/guides/caching.md#segment-config-options) option. ### Props The default export function receives the following props: #### `params` (optional) A promise that resolves to an object containing the [dynamic route parameters](/docs/app/api-reference/file-conventions/dynamic-routes.md) object from the root segment down to the segment `icon` or `apple-icon` is colocated in. > **Good to know**: If you use [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata.md), the function will also receive an `id` prop that is a promise resolving to the `id` value from one of the items returned by `generateImageMetadata`. ```tsx filename="app/shop/[slug]/icon.tsx" switcher export default async function Icon({ params, }: { params: Promise<{ slug: string }> }) { const { slug } = await params // ... } ``` ```jsx filename="app/shop/[slug]/icon.js" switcher export default async function Icon({ params }) { const { slug } = await params // ... } ``` | Route | URL | `params` | | ------------------------------- | ----------- | ---------------------------------- | | `app/shop/icon.js` | `/shop` | `undefined` | | `app/shop/[slug]/icon.js` | `/shop/1` | `Promise<{ slug: '1' }>` | | `app/shop/[tag]/[item]/icon.js` | `/shop/1/2` | `Promise<{ tag: '1', item: '2' }>` | ### Returns The default export function should return a `Blob` | `ArrayBuffer` | `TypedArray` | `DataView` | `ReadableStream` | `Response`. > **Good to know**: `ImageResponse` satisfies this return type. ### Config exports You can optionally configure the icon's metadata by exporting `size` and `contentType` variables from the `icon` or `apple-icon` route. | Option | Type | | ----------------------------- | --------------------------------------------------------------------------------------------------------------- | | [`size`](#size) | `{ width: number; height: number }` | | [`contentType`](#contenttype) | `string` - [image MIME type](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/MIME_types#image_types) | #### `size` ```tsx filename="icon.tsx | apple-icon.tsx" switcher export const size = { width: 32, height: 32 } export default function Icon() {} ``` ```jsx filename="icon.js | apple-icon.js" switcher export const size = { width: 32, height: 32 } export default function Icon() {} ``` ```html filename=" output" ``` #### `contentType` ```tsx filename="icon.tsx | apple-icon.tsx" switcher export const contentType = 'image/png' export default function Icon() {} ``` ```jsx filename="icon.js | apple-icon.js" switcher export const contentType = 'image/png' export default function Icon() {} ``` ```html filename=" output" ``` #### Route Segment Config `icon` and `apple-icon` are specialized [Route Handlers](/docs/app/api-reference/file-conventions/route.md) that can use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config.md) options as Pages and Layouts. ## Version History | Version | Changes | | --------- | ---------------------------------------------------- | | `v16.0.0` | `params` is now a promise that resolves to an object | | `v13.3.0` | `favicon` `icon` and `apple-icon` introduced | --- # Source: https://nextjs.org/docs/pages/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/app/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/pages/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/app/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/pages/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/app/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/pages/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/app/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/pages/guides/migrating/app-router-migration.md # Source: https://nextjs.org/docs/app/guides/migrating/app-router-migration.md # How to migrate from Pages to the App Router @doc-version: 16.0.4 This guide will help you: * [Update your Next.js application from version 12 to version 13](#nextjs-version) * [Upgrade features that work in both the `pages` and the `app` directories](#upgrading-new-features) * [Incrementally migrate your existing application from `pages` to `app`](#migrating-from-pages-to-app) ## Upgrading ### Node.js Version The minimum Node.js version is now **v18.17**. See the [Node.js documentation](https://nodejs.org/docs/latest-v18.x/api/) for more information. ### Next.js Version To update to Next.js version 13, run the following command using your preferred package manager: ```bash filename="Terminal" npm install next@latest react@latest react-dom@latest ``` ### ESLint Version If you're using ESLint, you need to upgrade your ESLint version: ```bash filename="Terminal" npm install -D eslint-config-next@latest ``` > **Good to know**: You may need to restart the ESLint server in VS Code for the ESLint changes to take effect. Open the Command Palette (`cmd+shift+p` on Mac; `ctrl+shift+p` on Windows) and search for `ESLint: Restart ESLint Server`. ## Next Steps After you've updated, see the following sections for next steps: * [Upgrade new features](#upgrading-new-features): A guide to help you upgrade to new features such as the improved Image and Link Components. * [Migrate from the `pages` to `app` directory](#migrating-from-pages-to-app): A step-by-step guide to help you incrementally migrate from the `pages` to the `app` directory. ## Upgrading New Features Next.js 13 introduced the new [App Router](/docs/app.md) with new features and conventions. The new Router is available in the `app` directory and co-exists with the `pages` directory. Upgrading to Next.js 13 does **not** require using the App Router. You can continue using `pages` with new features that work in both directories, such as the updated [Image component](#image-component), [Link component](#link-component), [Script component](#script-component), and [Font optimization](#font-optimization). ### `` Component Next.js 12 introduced new improvements to the Image Component with a temporary import: `next/future/image`. These improvements included less client-side JavaScript, easier ways to extend and style images, better accessibility, and native browser lazy loading. In version 13, this new behavior is now the default for `next/image`. There are two codemods to help you migrate to the new Image Component: * [**`next-image-to-legacy-image` codemod**](/docs/app/guides/upgrading/codemods.md#next-image-to-legacy-image): Safely and automatically renames `next/image` imports to `next/legacy/image`. Existing components will maintain the same behavior. * [**`next-image-experimental` codemod**](/docs/app/guides/upgrading/codemods.md#next-image-experimental): Dangerously adds inline styles and removes unused props. This will change the behavior of existing components to match the new defaults. To use this codemod, you need to run the `next-image-to-legacy-image` codemod first. ### `` Component The [`` Component](/docs/app/api-reference/components/link.md) no longer requires manually adding an `
` tag as a child. This behavior was added as an experimental option in [version 12.2](https://nextjs.org/blog/next-12-2) and is now the default. In Next.js 13, `` always renders `` and allows you to forward props to the underlying tag. For example: ```jsx import Link from 'next/link' // Next.js 12: `` has to be nested otherwise it's excluded About // Next.js 13: `` always renders `` under the hood About ``` To upgrade your links to Next.js 13, you can use the [`new-link` codemod](/docs/app/guides/upgrading/codemods.md#new-link). ### ` ``` Or by using the `dangerouslySetInnerHTML` property: ```jsx