Next.js Docs

Summary: This page is the main documentation index for Next.js, providing an overview of what Next.js is, how to use the docs, the difference between App Router and Pages Router, prerequisites, accessibility…

What is Next.js?

Next.js is a React framework for building full-stack web applications. You use React Components to build user interfaces, and Next.js for additional features and optimizations. It also automatically…

How to use the docs

The docs are organized into 3 sections:

- Getting Started: Step-by-step tutorials to help you create a new application and learn the core Next.js features.
- Guides: Tutorials on specific use cases,…

App Router and Pages Router

Next.js has two different routers:

- App Router: The newer router that supports new React features like Server Components.
- Pages Router: The original router, still supported and being…

React version handling

The App Router and Pages Router handle React versions differently:

- App Router: Uses React canary releases built-in, which include all the stable React 19 changes, as well as newer features being…

Pre-requisite knowledge

Our documentation assumes some familiarity with web development. Before getting started, it'll help if you're comfortable with:

- HTML
- CSS
- JavaScript
- React

If you're new to React or need a…

Accessibility

For the best experience when using a screen reader, we recommend using Firefox and NVDA, or Safari and VoiceOver.

Join our Community

If you have questions about anything related to Next.js, you're always welcome to ask our community on GitHub Discussions, Discord, X (Twitter), and Reddit.

Next Steps

Create your first application and learn the core Next.js features.


App Router

Summary: Overview of the Next.js App Router, a file-system based router that leverages React's latest features such as Server Components, Suspense, and Server Functions.

App Router

The App Router is a file-system based router that uses React's latest features such as Server Components, Suspense, and Server Functions.

Next Steps

Learn the fundamentals of building an App Router project, from installation to layouts, navigation, server and client components.

- Installation: Learn how to create a new Next.js application with…


API Reference

Summary: Index page for Next.js App Router API references, listing categories such as Directives, Components, File-system conventions, Functions, Configuration, CLI, Adapters, Edge Runtime, and Turbopack.

Directives

Directives are used to modify the behavior of your Next.js application.

Components

API Reference for Next.js built-in components.

File-system conventions

API Reference for Next.js file-system conventions.

Functions

API Reference for Next.js Functions and Hooks.

Configuration

Learn how to configure Next.js applications.

CLI

API Reference for the Next.js Command Line Interface (CLI) tools.

Adapters

Build deployment adapters for Next.js platforms and infrastructure.

Edge Runtime

API Reference for the Edge Runtime.

Turbopack

Turbopack is an incremental bundler optimized for JavaScript and TypeScript, written in Rust, and built into Next.js.


Adapters

Summary: Overview of Next.js deployment adapter documentation, covering configuration, creation, API reference, testing, routing, PPR, runtime integration, entrypoints, output types, routing information, use…

Adapters

Use this section to build and validate deployment adapters that integrate with the Next.js build and runtime model.

Configuration

Configure `adapterPath` or `NEXT_ADAPTER_PATH` to use a custom deployment adapter.

Creating an Adapter

Create an adapter module that implements the `NextAdapter` interface.

API Reference

Reference for `modifyConfig` and `onBuildComplete` in the `NextAdapter` interface.

Testing Adapters

Validate adapters with the Next.js compatibility test harness and custom lifecycle scripts.

Routing with @next/routing

Use `@next/routing` to apply Next.js route matching behavior in adapters.

Implementing PPR in an Adapter

Implement Partial Prerendering support in an adapter using fallback output and cache hooks.

Runtime Integration

Understand how build-time adapters and runtime cache interfaces work together.

Invoking Entrypoints

Invoke Node.js and Edge build entrypoints with adapter runtime context.

Output Types

Reference for all build output types exposed to adapters.

Routing Information

Reference for routing phases and route fields exposed in `onBuildComplete`.

Use Cases

Common patterns and examples for deployment adapter implementations.

Supporting Immutable Static Assets

Support immutable static assets in an adapter


API Reference

Summary: This page describes the Next.js adapter API, including functions to modify configuration and handle build completion.

`async modifyConfig(config, context)`

Called for any CLI command that loads the `next.config.js` file to allow modification of the configuration.

**Parameters:**

- `config`: The complete Next.js configuration object
- `context.phase`:…

`async onBuildComplete(context)`

Called after the build process completes with detailed information about routes and outputs.

**Parameters:**

- `context.routing`: Object containing Next.js routing phases and metadata
-…

context.phase

The current build phase (see phases)

context.nextVersion

Version of Next.js being used

context.projectDir

Absolute path to the Next.js project directory

context.routing.beforeMiddleware

Routes executed before middleware (includes header and redirect handling)

context.routing.beforeFiles

Rewrite routes checked before filesystem route matching

context.routing.afterFiles

Rewrite routes checked after filesystem route matching

context.routing.dynamicRoutes

Dynamic route matching table

context.routing.onMatch

Routes applied after a successful match (for example immutable static asset cache headers)

context.routing.fallback

Final rewrite fallback routes

context.routing.shouldNormalizeNextData

Whether `/_next/data/<buildId>/...` URLs should be normalized during matching

context.routing.rsc

Route metadata used for React Server Components routing behavior

context.outputs

Detailed information about all build outputs organized by type

context.repoRoot

Absolute path to the detected repository root

context.distDir

Absolute path to the build output directory

context.config

The final Next.js configuration (with modifyConfig applied)

context.buildId

Unique identifier for the current build


Configuration

Summary: This page describes how to configure Next.js adapters by specifying the adapter module path via `adapterPath` in `next.config.js` or the `NEXT_ADAPTER_PATH` environment variable.

Configuration

To use an adapter, specify the path to your adapter module in `adapterPath`:

Alternatively `NEXT_ADAPTER_PATH` can be set to enable zero-config usage in deployment platforms.

/** @type {import('next').NextConfig} */
const nextConfig = {
  adapterPath: require.resolve('./my-adapter.js'),
}

module.exports = nextConfig

adapterPath

Path to the adapter module. Specify the path to your adapter module in `adapterPath`.

Environment variable that can be set to enable zero-config usage in deployment platforms.


Creating an Adapter

Summary: This page explains how to create a custom adapter for Next.js by implementing the NextAdapter interface, including the interface definition and a minimal example.

Creating an Adapter

An adapter is a module that exports an object implementing the `NextAdapter` interface.

The interface can be imported from the `next` package:

The interface is defined as follows:

type Route = {
  source?: string
  sourceRegex: string
  destination?: string
  headers?: Record<string, string>
  has?: RouteHas[]
  missing?: RouteHas[]
  status?: number
  priority?: boolean
}…

Basic Adapter Structure

Here's a minimal adapter example:

/** @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…


Adapters: Supporting Immutable Static Assets | Next.js

Summary: Explains how Next.js adapters can support immutable static assets, including the `supportsImmutableAssets` config flag, the shared-namespace runtime behavior of immutable assets, content-hash…

Supporting Immutable Static Assets

See [`config.supportsImmutableAssets`](/docs/app/api-reference/config/next-config-js/supportsImmutableAssets) for end-user-facing information about this feature.

When…

Adapter Implementation

You need to:

- In the `modifyConfig`, set the `config.supportsImmutableAssets` property to `true` (if it's not already set to `false` by the user) to signal that you support deploying immutable…

/** @type {import('next').NextAdapter} */
const adapter = {
  name: 'my-custom-adapter',

  async modifyConfig(config, { phase }) {
    if (phase === 'phase-production-build') {…


Implementing PPR in an Adapter

Summary: This page explains how to implement Partial Prerendering (PPR) in a Next.js adapter, covering build-time seeding of fallback shells and postponed state, runtime streaming of cached shells with…

Overview

For partially prerendered app routes, `onBuildComplete` gives you the data needed to seed and resume PPR:

- `outputs.prerenders[].fallback.filePath`: path to the generated fallback shell (for…

1. Seed shell + postponed state at build time

import { readFile } from 'node:fs/promises'

async function seedPprEntries(outputs: AdapterOutputs) {
  for (const prerender of outputs.prerenders) {
    const fallback = prerender.fallback
    if…

2. Runtime flow: serve cached shell and resume in background

At request time, you can stream a single response that is the concatenation of:

- cached HTML shell stream
- resumed render stream (generated after invoking `handler` with postponed state)

Client
  | GET /ppr-route
  v
Adapter Router
  |
  |-- read cached shell + postponedState ---> Platform Cache
  |<------------- cache hit -----------------|
  |
  |-- create responseStream =…

3. Update cache with `requestMeta.onCacheEntryV2`

`requestMeta.onCacheEntryV2` is called when a response cache entry is looked up or generated. Use it to persist updated shell/postponed data.

- `requestMeta.onCacheEntry` still works, but is…

await handler(req, res, {
  waitUntil,
  requestMeta: {
    postponed: cachedPprEntry?.postponedState,
    onCacheEntryV2: async (cacheEntry, meta) => {
      if (cacheEntry.value?.kind ===…

Entrypoint (handler)
  | onCacheEntryV2(cacheEntry, { url })
  v
requestMeta.onCacheEntryV2 callback
  |
  |-- if APP_PAGE ---> persist html + postponedState + headers ---> Platform Cache
  |
  '--…


Adapters: Invoking Entrypoints | Next.js

Summary: This page describes how build output entrypoints use a `handler(..., ctx)` interface for Node.js and Edge runtimes, including how adapters can invoke entrypoints directly and use `requestMeta`…

Invoking Entrypoints

Build output entrypoints use a `handler(..., ctx)` interface, with runtime-specific request/response types.

Node.js runtime (`runtime: 'nodejs'`)

Node.js entrypoints use the following interface:

When invoking Node.js entrypoints directly, adapters can pass helpers directly on `requestMeta` instead of relying on internals. Some of the…

handler(
  req: IncomingMessage,
  res: ServerResponse,
  ctx: {
    waitUntil?: (promise: Promise<void>) => void
    requestMeta?: RequestMeta
  }
): Promise<void>

await handler(req, res, {
  requestMeta: {
    // Relative path from process.cwd() to the Next.js project directory.
    relativeProjectDir: '.',
    // Optional hostname used by route handlers when…

Edge runtime (`runtime: 'edge'`) (deprecated)

> The Edge Runtime is [deprecated](/docs/messages/edge-runtime-deprecated). New routes should use the Node.js runtime.

Edge entrypoints use the following interface:

The shape is aligned around…

handler(
  request: Request,
  ctx: {
    waitUntil?: (prom: Promise<void>) => void
    signal?: AbortSignal
    requestMeta?: RequestMeta
  }
): Promise<Response>

{
  modulePath: string // Absolute path to the module registered in the edge runtime
  entryKey: string // Canonical key used by the edge entry registry
  handlerExport: string // Export name to…

const entry = await globalThis._ENTRIES[output.edgeRuntime.entryKey]
const handler = entry[output.edgeRuntime.handlerExport]
await handler(request, ctx)


Adapters: Output Types

Summary: Describes the `outputs` object structure exposed to Next.js adapters, including arrays for pages, API routes, app pages, app routes, prerenders, static files, and middleware, with TypeScript type…

Output Types

The `outputs` object contains arrays of build output types:

- `outputs.pages`: React pages from the `pages/` directory
- `outputs.pagesApi`: API routes from `pages/api/`
- `outputs.appPages`: React…

Pages (`outputs.pages`)

React pages from the `pages/` directory:

{
  type: 'PAGES'
  id: string           // Route identifier
  filePath: string     // Path to the built file
  pathname: string     // URL pathname
  sourcePage: string   // Original source file…

API Routes (`outputs.pagesApi`)

API routes from `pages/api/`:

{
  type: 'PAGES_API'
  id: string           // Route identifier
  filePath: string     // Path to the built file
  pathname: string     // URL pathname
  sourcePage: string   // Original relative…

App Pages (`outputs.appPages`)

React pages from the `app/` directory:

{
  type: 'APP_PAGE'
  id: string           // Route identifier
  filePath: string     // Path to the built file
  pathname: string     // URL pathname. Includes .rsc suffix for RSC routes…

App Routes (`outputs.appRoutes`)

API and metadata routes from the `app/` directory:

{
  type: 'APP_ROUTE'
  id: string           // Route identifier
  filePath: string     // Path to the built file
  pathname: string     // URL pathname
  sourcePage: string   // Original relative…

Prerenders (`outputs.prerenders`)

ISR-enabled routes and static prerenders:

{
  type: 'PRERENDER'
  id: string           // Route identifier
  pathname: string     // URL pathname
  parentOutputId: string  // ID of the source page/route
  groupId: number        //…

Prerender classification

`routeType`, `response`, and `compute` are emitted together on the primary response in a prerender group. Related RSC, data, and segment outputs omit these fields. Pages Router templates with…

Static Files (`outputs.staticFiles`)

Static assets and auto-statically optimized pages:

See [Supporting immutable static assets](/docs/app/api-reference/adapters/immutable-static-assets) for more information about `immutableHash`.

{
  type: 'STATIC_FILE'
  id: string // Unique identifier for this static file output
  filePath: string // Absolute filesystem path to the built file
  pathname: string // The routable URL pathname…

Middleware (`outputs.middleware`)

`middleware.ts` (`.js`/`.ts`) or `proxy.ts` (`.js`/`.ts`) function (if present):

{
  type: 'MIDDLEWARE'
  id: string           // Route identifier
  filePath: string     // Path to the built file
  pathname: string      // Always '/_middleware'
  sourcePage: string    // Always…

outputs.pages

React pages from the `pages/` directory

outputs.pagesApi

API routes from `pages/api/`

outputs.appPages

React pages from the `app/` directory

outputs.appRoutes

API and metadata routes from `app/`

outputs.middleware

Middleware function (if present)


Adapters: Routing Information

Summary: Describes the `routing` object available in `onBuildComplete`, including the route phases and common fields that make up deployment-ready routing information.

Routing Information

The `routing` object in `onBuildComplete` provides complete routing information with processed patterns ready for deployment:

routing.beforeMiddleware

Routes applied before middleware execution. These include generated header and redirect behavior.

routing.beforeFiles

Rewrite routes checked before filesystem route matching.

routing.afterFiles

Rewrite routes checked after filesystem route matching.

routing.dynamicRoutes

Dynamic matchers generated from route segments such as `[slug]` and catch-all routes.

routing.onMatch

Routes that apply after a successful match, such as immutable cache headers for hashed static assets.

routing.fallback

Final rewrite routes checked when earlier phases did not produce a match.

Common Route Fields

Each route entry can include:

- `source`: Original route pattern (optional for generated internal rules)
- `sourceRegex`: Compiled regex for matching requests
- `destination`: Internal destination…


Routing with @next/routing

Summary: Explains how to use the `@next/routing` package's `resolveRoutes()` function to reproduce Next.js route matching behavior with data from `onBuildComplete`.

Routing with @next/routing

You can use `@next/routing` to reproduce Next.js route matching behavior with data from `onBuildComplete`.

`resolveRoutes()` returns:

- `middlewareResponded`: `true` when middleware already sent a…

import { resolveRoutes } from '@next/routing'

const pathnames = [
  ...outputs.pages,
  ...outputs.pagesApi,
  ...outputs.appPages,
  ...outputs.appRoutes,
  ...outputs.staticFiles,
].map((output)…

url

The request URL as a URL object.

buildId

The build ID for the deployment.

basePath

The base path of the Next.js application.

The i18n configuration object.

headers

The request headers as a Headers object.

requestBody

The request body as a ReadableStream.

pathnames

An array of pathnames from the build output.

routes

The routing configuration from the build.

invokeMiddleware

An async function to invoke middleware, returning a response object.


Runtime Integration

Summary: Describes the runtime behavior of Next.js server and cache interfaces, and how adapters interact with them, including handler context and PPR chain headers.

Overview

The Deployment Adapter API is a **build-time** interface. It tells your platform what was built and how to route requests. **Runtime** behavior (request handling, streaming, caching) is handled by…

Handler Context

When invoking entrypoints, adapters pass a `ctx` object to the Next.js handler. Key fields include:

- **`ctx.waitUntil`**: a function that accepts a promise. Use this to keep the serverless function…

PPR Chain Headers

In the [prerenders output type](/docs/app/api-reference/adapters/output-types#prerenders-outputsprerenders), `pprChain.headers` contains the headers needed for the [resume…


Testing Adapters

Summary: Next.js provides a test harness for validating adapters, including end-to-end tests for deployment. This page describes the environment variables and script contracts required for custom deploy,…

Testing Adapters

Next.js provides a test harness for validating adapters. Running the end-to-end tests for deployment.

Example GitHub Actions workflow:

The test harness looks for these environment variables:

-…

name: test-e2e-deploy

on:
  workflow_dispatch:
    inputs:
      nextjsRef:
        description: 'Next.js repo ref (branch/tag/SHA)'
        default: 'canary'
        type: string
  # schedule:
  #…

Custom deploy script contract

The deploy script `NEXT_TEST_DEPLOY_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness.

The deploy script must follow this contract:

- Exit…

#!/usr/bin/env bash
set -euo pipefail

# Install the adapter, build the app, and deploy or start it.
node -e "
const…

Custom logs script contract

The logs script `NEXT_TEST_DEPLOY_LOGS_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness.

Additionally it receives `NEXT_TEST_DIR` and…

#!/usr/bin/env bash
set -euo pipefail

if [ -f ".adapter-build.log" ]; then
  cat ".adapter-build.log"
fi

if [ -f ".adapter-server.log" ]; then
  echo "=== .adapter-server.log ==="
  cat…

Custom cleanup script contract

The cleanup script `NEXT_TEST_CLEANUP_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness.

Additionally it receives `NEXT_TEST_DIR` and…


Adapters: Use Cases | Next.js

Summary: Common use cases for Next.js adapters, including deployment platform integration, asset processing, monitoring, custom bundling, build validation, and route generation.

Use Cases

Common use cases for adapters include:

- **Deployment Platform Integration** : Automatically configure build outputs for specific hosting platforms

- **Asset Processing** : Transform or optimize…


API Reference: CLI | Next.js

Summary: Overview of the two Next.js Command Line Interface (CLI) tools: create-next-app and next, with links to their API references.

CLI

Next.js comes with **two** Command Line Interface (CLI) tools:

- **`create-next-app`**: Quickly create a new Next.js application using the default template or an…

create-next-app

Create Next.js apps using one command with the create-next-app CLI.

next CLI

Learn how to run and build your application with the Next.js CLI.


create-next-app

Summary: The create-next-app CLI allows you to create a new Next.js application using the default template or an example from a public GitHub repository. It is the easiest way to get started with Next.js.

Basic usage

pnpm create next-app [project-name] [options]

Reference

The following options are available:

Examples

With the default template

To create a new app using the default template, run the following command in your terminal:

On installation, you'll see the following prompts:

If you choose to `customize settings`, you'll see the…

What is your project named? my-app
Would you like to use the recommended Next.js defaults?
    Yes, use recommended defaults - TypeScript, ESLint, Tailwind CSS, App Router, AGENTS.md
    No, reuse…

Would you like to use TypeScript? No / Yes
Which linter would you like to use? ESLint / Biome / None
Would you like to use React Compiler? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would…

Linter Options

**ESLint** : The traditional and most popular JavaScript linter. Includes Next.js-specific rules from `@next/eslint-plugin-next`.

 **Biome** : A fast, modern linter and formatter that combines the…

With an official Next.js example

To create a new app using an official Next.js example, use the `--example` flag. For example:

You can view a list of all available examples along with setup instructions in the [Next.js…

pnpm create next-app --example [example-name] [your-project-name]

With any public GitHub example

To create a new app using any public GitHub example, use the `--example` option with the GitHub repository's URL. For example:

pnpm create next-app --example "https://github.com/.../" [your-project-name]

-h or --help

Show all available options

-v or --version

Output the version number

--no-*

Negate default options. E.g. --no-ts

--ts or --typescript

Initialize as a TypeScript project

--js or --javascript

Initialize as a JavaScript project

--tailwind

Initialize with Tailwind CSS config

--react-compiler

Initialize with React Compiler enabled

--eslint

Initialize with ESLint config

--biome

Initialize with Biome config

--no-linter

Skip linter configuration

--app

Initialize as an App Router project

--api

Initialize a project with only route handlers

--src-dir

Initialize inside a src/ directory

--turbopack

Force enable Turbopack in generated package.json

--webpack

Force enable Webpack in generated package.json

--import-alias <alias-to-configure>

Specify import alias to use

--empty

Initialize an empty project

--use-npm

Explicitly tell the CLI to bootstrap the application using npm

--use-pnpm

Explicitly tell the CLI to bootstrap the application using pnpm

--use-yarn

Explicitly tell the CLI to bootstrap the application using Yarn

--use-bun

Explicitly tell the CLI to bootstrap the application using Bun

-e or --example [name] [github-url]

An example to bootstrap the app with

--example-path <path-to-example>

Specify the path to the example separately

--reset-preferences

Explicitly tell the CLI to reset any stored preferences

--skip-install

Explicitly tell the CLI to skip installing packages

--disable-git

Explicitly tell the CLI to disable git initialization

--agents-md

Include AGENTS.md and CLAUDE.md to guide coding agents

--yes

Use previous preferences or defaults for all options


next CLI

Summary: The Next.js CLI allows you to develop, build, start your application, and more. It provides commands like dev, build, start, info, telemetry, typegen, upgrade, and experimental-analyze.

Basic Usage

The Next.js CLI allows you to develop, build, start your application, and more. Basic usage:

> **Good to know** : With `npm run`, use `--` before CLI flags so npm forwards them to `next`. This is…

Reference

The following options are available:

| Options | Description |
| --- | --- |
| `-h` or `--help` | Shows all available options |
| `-v` or `--version` | Outputs the Next.js version number |

Commands

The following commands are available:

| Command | Description |
| --- | --- |
| [`dev`](#next-dev-options) | Starts Next.js in development mode with Hot Module Reloading, error reporting, and more.…

next dev options

`next dev` starts the application in development mode with Hot Module Reloading (HMR), error reporting, and more.

> **Good to know** : Development builds output to `.next/dev` instead of `.next`.…

next build options

`next build` creates an optimized production build of your application. The output displays information about each route. For example:

```
Route (app)
┌ ○ /_not-found
└ ƒ /products/[id]

○…

Route (app)
┌ ○ /_not-found
└ ƒ /products/[id]

○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand

next start options

`next start` starts the application in production mode. The application should be compiled with [`next build`](#next-build-options) first.

The following options are available for the `next start`…

next info options

`next info` prints relevant details about the current system which can be used to report Next.js bugs when opening a [GitHub issue](https://github.com/vercel/next.js/issues). This information…

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.6.0
  Available memory (MB): 65536
  Available CPU cores: 10
Binaries:
  Node: 20.12.0
  npm: 10.5.0
  Yarn:…

next telemetry options

Next.js collects  **completely anonymous**  telemetry data about general usage. Participation in this anonymous program is optional, and you can opt-out if you prefer not to share information.

The…

next typegen options

`next typegen` generates TypeScript definitions for your application's routes without performing a full build. This is useful for IDE autocomplete and CI type-checking of route usage.

Previously,…

# Generate route types first, then validate with TypeScript
next typegen && tsc --noEmit

# Or in CI workflows for type checking without building
next typegen && npm run type-check

next typegen
# or for a specific app
next typegen ./apps/web

next upgrade options

`next upgrade` upgrades your Next.js application to the latest version.

The following options are available for the `next upgrade` command:

| Option | Description |
| --- | --- |
| `-h, --help` |…

next experimental-analyze options

`next experimental-analyze` analyzes your application's bundle output using [Turbopack](/docs/app/api-reference/turbopack). This command helps you understand the size and composition of your bundles,…

# Write output to .next/diagnostics/analyze
npx next experimental-analyze --output

# Copy the output for comparison with a future analysis
cp -r .next/diagnostics/analyze ./analyze-before-refactor

Debugging prerender errors

If you encounter prerendering errors during `next build`, you can pass the `--debug-prerender` flag to get more detailed output:

```
next build --debug-prerender
```

This enables several…

Building specific routes

You can build only specific routes in the App and Pages Routers using the `--debug-build-paths` option. This is useful for faster debugging when working with large applications. The…

# Build a specific route
next build --debug-build-paths="app/page.tsx"

# Build more than one route
next build --debug-build-paths="app/page.tsx,pages/index.tsx"

# Include route group folders in the…

Changing the default port

By default, Next.js uses `http://localhost:3000` during development and with `next start`. The default port can be changed with the `-p` option, like so:

```
next dev -p 4000
```

Or using the…

Using HTTPS during development

For certain use cases like webhooks or authentication, you can use [HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS) to have a secure environment on `localhost`. Next.js can generate a…

next dev --experimental-https --experimental-https-key ./certificates/localhost-key.pem --experimental-https-cert ./certificates/localhost.pem

Configuring a timeout for downstream proxies

When deploying Next.js behind a downstream proxy (e.g. a load-balancer like AWS ELB/ALB), it's important to configure Next's underlying HTTP server with [keep-alive…

Passing Node.js arguments

You can pass any [node arguments](https://nodejs.org/api/cli.html#cli_node_options_options) to `next` commands. For example:

```
NODE_OPTIONS='--throw-deprecation' next
NODE_OPTIONS='-r esm'…

NODE_OPTIONS='--throw-deprecation' next
NODE_OPTIONS='-r esm' next
NODE_OPTIONS='--inspect' next

CPU profiling

You can capture CPU profiles to analyze performance bottlenecks in your Next.js application. The `--experimental-cpu-prof` flag enables V8's built-in CPU profiler and saves profiles to…

# Profile the build process
next build --experimental-cpu-prof

# Profile the dev server (profile saved on Ctrl+C or SIGTERM)
next dev --experimental-cpu-prof

# Profile the production server
next…

Version History

| Version | Changes |
| --- | --- |
| `v16.1.0` | Add the `next upgrade` command |
| `v16.1.0` | Add the `next experimental-analyze` command |
| `v16.0.0` | The JS bundle size metrics have been…

global -h, --help

Shows all available options

global -v, --version

Outputs the Next.js version number

dev -h, --help

Show all available options.

dev [directory]

A directory in which to build the application. If not provided, current directory is used.

dev --turbopack

Force enable Turbopack (enabled by default). Also available as --turbo.

dev --webpack

Use Webpack instead of the default Turbopack bundler for development.

dev -p, --port

Specify a port number on which to start the application. Default: 3000, env: PORT

dev -H, --hostname

Specify a hostname on which to start the application. Useful for making the application available for other devices on the network. Default: 0.0.0.0

dev --experimental-https

Starts the server with HTTPS and generates a self-signed certificate.

dev --experimental-https-key

Path to a HTTPS key file.

dev --experimental-https-cert

Path to a HTTPS certificate file.

dev --experimental-https-ca

Path to a HTTPS certificate authority file.

dev --experimental-upload-trace

Reports a subset of the debugging trace to a remote HTTP URL.

dev --experimental-cpu-prof

Enables CPU profiling using V8's inspector. Profiles are saved to .next-profiles/ on exit.

build -h, --help

Show all available options.

build [directory]

A directory on which to build the application. If not provided, the current directory will be used.

build --webpack

Build using Webpack.

build -d, --debug

Enables a more verbose build output. With this flag enabled additional build output like rewrites, redirects, and headers will be shown.

build --profile

Enables production profiling for React.

build --no-lint

Disables linting. Note: linting will be removed from next build in Next 16. If you're using Next 15.5+ with a linter other than eslint, linting during build will not occur.

build --no-mangling

Disables mangling. This may affect performance and should only be used for debugging purposes.

build --experimental-app-only

Builds only App Router routes.

build --experimental-build-mode

Uses an experimental build mode. (choices: "compile", "generate", default: "default")

build --debug-prerender

Debug prerender errors in development.

build --debug-build-paths

Build only specific routes for debugging.

start -h, --help

Show all available options.

start [directory]

A directory on which to start the application. If no directory is provided, the current directory will be used.

start -p, --port

Specify a port number on which to start the application. (default: 3000, env: PORT)

start -H, --hostname

Specify a hostname on which to start the application (default: 0.0.0.0).

start --keepAliveTimeout

Specify the maximum amount of milliseconds to wait before closing the inactive connections.

info -h, --help

Show all available options

info --verbose

Collects additional information for debugging.

telemetry -h, --help

Show all available options.

telemetry --enable

Enables Next.js' telemetry collection.

telemetry --disable

Disables Next.js' telemetry collection.

typegen -h, --help

Show all available options.

typegen [directory]

A directory on which to generate types. If not provided, the current directory will be used.

upgrade -h, --help

Show all available options.

upgrade [directory]

A directory with the Next.js application to upgrade. If not provided, the current directory will be used.

upgrade --revision

Specify a Next.js version or tag to upgrade to (e.g., latest, canary, 15.0.0). Defaults to the release channel you have currently installed.

upgrade --verbose

Show verbose output during the upgrade process.

experimental-analyze -h, --help

Show all available options.

experimental-analyze [directory]

A directory on which to analyze the application. If not provided, the current directory will be used.

experimental-analyze --profile

Enables production profiling for React. This may affect performance.

experimental-analyze -o, --output

Write analysis files to disk without starting the server. Output is written to .next/diagnostics/analyze.

experimental-analyze --port

Specify a port number to serve the analyzer on. (default: 4000, env: PORT)


Components

Summary: This page provides an index of Next.js built-in components for optimizing fonts, forms, images, links, and scripts.

Components

This page is also available as Markdown: request this page's URL with an `Accept: text/markdown` header. For an index of Next.js documentation, see [/docs/llms.txt](/docs/llms.txt).

- [Font:…


Font Module

Summary: This page documents the Next.js Font Module (`next/font`), which automatically optimizes fonts, self-hosts font files, and provides built-in support for Google Fonts. It covers the API reference for…

Reference

The following table lists the available options for the font loader functions. The columns indicate which loader (`font/google` or `font/local`) each option applies to, the type, and whether it is…

src

The path of the font file as a string or an array of objects (with type `Array<{path: string, weight?: string, style?: string}>`) relative to the directory where the font loader function is…

weight

The font [`weight`](https://fonts.google.com/knowledge/glossary/weight) with the following possibilities:

- A string with possible values of the weights available for the specific font or a range of…

style

The font [`style`](https://developer.mozilla.org/docs/Web/CSS/font-style) with the following possibilities:

- A string [value](https://developer.mozilla.org/docs/Web/CSS/font-style#values) with…

subsets

The font [`subsets`](https://fonts.google.com/knowledge/glossary/subsetting) defined by an array of string values with the names of each subset you would like to be…

axes

Some variable fonts have extra `axes` that can be included. By default, only the font weight is included to keep the file size down. The possible values of `axes` depend on the specific font.

Used…

display

The font [`display`](https://developer.mozilla.org/docs/Web/CSS/@font-face/font-display) with possible string [values](https://developer.mozilla.org/docs/Web/CSS/@font-face/font-display#values) of…

preload

A boolean value that specifies whether the font should be [preloaded](/docs/app/api-reference/components/font#preloading) or not. The default is `true`.

Used in `next/font/google` and…

fallback

The fallback font to use if the font cannot be loaded. An array of strings of fallback fonts with no default.

- Optional

Used in `next/font/google` and `next/font/local`

Examples:

- `fallback:…

adjustFontFallback

- For `next/font/google`: A boolean value that sets whether an automatic fallback font should be used to reduce [Cumulative Layout Shift](https://web.dev/cls/). The default is `true`.

- For…

variable

A string value to define the CSS variable name to be used if the style is applied with the [CSS variable method](#css-variables).

Used in `next/font/google` and `next/font/local`

-…

declarations

An array of font face [descriptor](https://developer.mozilla.org/docs/Web/CSS/@font-face#descriptors) key-value pairs that define the generated `@font-face` further.

Used in `next/font/local`

-…

Examples

Google Fonts

To use a Google font, import it from `next/font/google` as a function. We recommend using [variable fonts](https://fonts.google.com/variablefonts) for the best performance and flexibility.

If you…

import { Inter } from 'next/font/google'

// If loading a variable font, you don't need to specify the font weight
const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
})

export default…

import { Roboto } from 'next/font/google'

const roboto = Roboto({
  weight: '400',
  subsets: ['latin'],
  display: 'swap',
})

export default function RootLayout({
  children,
}: {
  children:…

const roboto = Roboto({
  weight: ['400', '700'],
  style: ['normal', 'italic'],
  subsets: ['latin'],
  display: 'swap',
})

Specifying a subset

Google Fonts are automatically [subset](https://fonts.google.com/knowledge/glossary/subsetting). This reduces the size of the font file and improves performance. You'll need to define which of these…

const inter = Inter({ subsets: ['latin'] })

Using Multiple Fonts

You can import and use multiple fonts in your application. There are two approaches you can take.

The first approach is to create a utility function that exports a font, imports it, and applies its…

import { Inter, Roboto_Mono } from 'next/font/google'

export const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
})

export const roboto_mono = Roboto_Mono({
  subsets: ['latin'],…

import { inter } from './fonts'

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.className}>
      <body>…

import { roboto_mono } from './fonts'

export default function Page() {
  return (
    <>

My page

    </>
  )
}

import { Inter, Roboto_Mono } from 'next/font/google'
import styles from './global.css'

const inter = Inter({
  subsets: ['latin'],
  variable: '--font-inter',
  display: 'swap',
})

const…

html {
  font-family: var(--font-inter);
}

h1 {
  font-family: var(--font-roboto-mono);
}

Local Fonts

Import `next/font/local` and specify the `src` of your local font file. We recommend using [variable fonts](https://fonts.google.com/variablefonts) for the best performance and flexibility.

If you…

import localFont from 'next/font/local'

// Font files can be colocated inside of `app`
const myFont = localFont({
  src: './my-font.woff2',
  display: 'swap',
})

export default function…

const roboto = localFont({
  src: [
    {
      path: './Roboto-Regular.woff2',
      weight: '400',
      style: 'normal',
    },
    {
      path: './Roboto-Italic.woff2',
      weight: '400',…

With Tailwind CSS

`next/font` integrates seamlessly with [Tailwind CSS](https://tailwindcss.com/) using [CSS variables](/docs/app/api-reference/components/font#css-variables).

In the example below, we use the `Inter`…

import { Inter, Roboto_Mono } from 'next/font/google'

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
})

const roboto_mono = Roboto_Mono({
  subsets:…

@import 'tailwindcss';

@theme inline {
  --font-sans: var(--font-inter);
  --font-mono: var(--font-roboto-mono);
}

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
    './app/**/*.{js,ts,jsx,tsx}',
  ],…

The quick brown fox ...

The quick brown fox ...

Applying Styles

You can apply the font styles in three ways:

- [`className`](#classname)
- [`style`](#style-1)
- [CSS Variables](#css-variables)

className

Returns a read-only CSS `className` for the loaded font to be passed to an HTML element.

CSS Variables

If you would like to set your styles in an external style sheet and specify additional options there, use the CSS variable method.

In addition to importing the font, also import the CSS file where…

import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'

const inter = Inter({
  variable: '--font-inter',
})

.text {
  font-family: var(--font-inter);
  font-weight: 200;
  font-style: italic;
}

Using a font definitions file

Every time you call the `localFont` or Google font function, that font will be hosted as one instance in your application. Therefore, if you need to use the same font in multiple places, you should…

import { Inter, Lora, Source_Sans_3 } from 'next/font/google'
import localFont from 'next/font/local'

// define your variable fonts
const inter = Inter()
const lora = Lora()
// define 2 weights of…

import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts'

export default function Page() {
  return (

Hello world using Inter…

import { greatVibes, sourceCodePro400 } from '@/fonts'

Preloading

When a font function is called on a page of your site, it is not globally available and preloaded on all routes. Rather, the font is only preloaded on the related routes based on the type of file…

Version Changes

The following table lists the version history for the Font Module.

src

The path of the font file as a string or an array of objects (with type `Array<{path: string, weight?: string, style?: string}>`) relative to the directory where the font loader function is called.…

weight

The font weight. A string with possible values of the weights available for the specific font or a range of values if it's a variable font. An array of weight values if the font is not a variable…

style

The font style. A string value with default value of `'normal'`. An array of style values if the font is not a variable google font (applies to `next/font/google` only). Optional.

subsets

The font subsets defined by an array of string values with the names of each subset you would like to be preloaded. Fonts specified via `subsets` will have a link preload tag injected into the head…

axes

Some variable fonts have extra `axes` that can be included. By default, only the font weight is included to keep the file size down. The possible values of `axes` depend on the specific font. Used in…

display

The font display property with possible string values of `'auto'`, `'block'`, `'swap'`, `'fallback'` or `'optional'` with default value of `'swap'`.

preload

A boolean value that specifies whether the font should be preloaded or not. The default is `true`.

adjustFontFallback

For `next/font/google`: A boolean value that sets whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The default is `true`. For `next/font/local`: A string or…

variable

A string value to define the CSS variable name to be used if the style is applied with the CSS variable method.

declarations

An array of font face descriptor key-value pairs that define the generated `@font-face` further. Used in `next/font/local`.


Form Component

Summary: The <Form> component extends the HTML <form> element to provide prefetching of loading UI, client-side navigation on submission, and progressive enhancement. It is useful for forms that update URL…

Overview

The `<Form>` component extends the HTML `<form>` element to provide **prefetching** of loading UI, **client-side navigation** on submission, and **progressive enhancement**. It's useful for forms…

import Form from 'next/form'

export default function Page() {
  return (
    <Form action="/search">
      {/* On submission, the input value will be appended to
          the URL, e.g.…

Reference

The behavior of the `<Form>` component depends on whether the `action` prop is passed a `string` or `function`.

- When `action` is a **string**, the `<Form>` behaves like a native HTML form that…

action (string) Props

When `action` is a string, the `<Form>` component supports the following props:

- **`action`** : The URL or path to navigate to when the form is submitted. An empty string `""` will navigate to the…

action (function) Props

When `action` is a function, the `<Form>` component supports the following prop:

- **`action`** : The Server Action to be called when the form is submitted. See the [React…

Caveats

- **`formAction`** : Can be used in a `<button>` or `<input type="submit">` fields to override the `action` prop. Next.js will perform a client-side navigation, however, this approach doesn't support…

Examples

Search form that leads to a search result page

You can create a search form that navigates to a search results page by passing the path as an `action`:

When the user updates the query input field and submits the form, the form data will be…

import Form from 'next/form'

export default function Page() {
  return (
    <Form action="/search">
      <input name="query" />
      <button type="submit">Submit</button>
    </Form>
  )
}

import { getSearchResults } from '@/lib/search'

export default async function SearchPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {…

export default function Loading() {
  return
Loading...

}

'use client'
import { useFormStatus } from 'react-dom'

export default function SearchButton() {
  const status = useFormStatus()
  return (
    <button type="submit">{status.pending ?…

import Form from 'next/form'
import { SearchButton } from '@/ui/search-button'

export default function Page() {
  return (
    <Form action="/search">
      <input name="query" />…

Mutations with Server Actions

You can perform mutations by passing a function to the `action` prop.

After a mutation, it's common to redirect to the new resource. You can use the [`redirect`](/docs/app/guides/redirecting)…

import Form from 'next/form'
import { createPost } from '@/posts/actions'

export default function Page() {
  return (
    <Form action={createPost}>
      <input name="title" />
      {/* ... */}…

'use server'
import { redirect } from 'next/navigation'

export async function createPost(formData: FormData) {
  // Create a new post
  // ...

  // Redirect to the new post…

import { getPost } from '@/posts/data'

export default async function PostPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const data = await getPost(id)…

action

The URL or path to navigate to when the form is submitted (string) or the Server Action to be called when the form is submitted (function). When a string, an empty string `""` navigates to the same…

replace

Replaces the current history state instead of pushing a new one to the browser's history stack. Only applies when `action` is a string. Default is `false`.

scroll

Controls the scroll behavior during navigation. Defaults to `true`, meaning it will scroll to the top of the new route and maintain scroll position for backwards/forwards navigation. Only applies…

prefetch

Controls whether the path should be prefetched when the form becomes visible in the user's viewport. Only applies when `action` is a string. Defaults to `true`.


Components: Image Component | Next.js

Summary: Extraction fallback content.

Components: Image Component | Next.js

This page is also available as Markdown: request this page's URL with an `Accept: text/markdown` header.   For an index of  Next.js documentation , see  [/docs/llms.txt](/docs/llms.txt).Copy page

##### Image Component

Last updated  May 4, 2026

The Next.js Image component extends the HTML `<img>` element for automatic image optimization.

app/page.js

##### Reference

###### Props

The following props are available:

| Prop | Example | Type | Status |
| --- | --- | --- | --- |

| [`src`](#src) | `src="/profile.png"` | String | Required |
| [`alt`](#alt) | `alt="Picture of the author"` | String | Required |
| [`width`](#width-and-height) | `width={500}` | Integer (px) | - |
| [`height`](#width-and-height) | `height={500}` | Integer (px) | - |
| [`fill`](#fill) | `fill={true}` | Boolean | - |
| [`loader`](#loader) | `loader={imageLoader}` | Function | - |
| [`sizes`](#sizes) | `sizes="(max-width: 768px) 100vw, 33vw"` | String | - |
| [`quality`](#quality) | `quality={80}` | Integer (1-100) | - |
| [`preload`](#preload) | `preload={true}` | Boolean | - |
| [`placeholder`](#placeholder) | `placeholder="blur"` | String | - |
| [`style`](#style) | `style={{objectFit: "contain"}}` | Object | - |
| [`onLoadingComplete`](#onloadingcomplete) | `onLoadingComplete={img => done())}` | Function | Deprecated |
| [`onLoad`](#onload) | `onLoad={event => done())}` | Function | - |
| [`onError`](#onerror) | `onError(event => fail()}` | Function | - |
| [`loading`](#loading) | `loading="lazy"` | String | - |
| [`blurDataURL`](#blurdataurl) | `blurDataURL="data:image/jpeg..."` | String | - |
| [`unoptimized`](#unoptimized) | `unoptimized={true}` | Boolean | - |
| [`overrideSrc`](#overridesrc) | `overrideSrc="/seo.png"` | String | - |
| [`decoding`](#decoding) | `decoding="async"` | String | - |

###### `src`

The source of the image. Can be one of the following:

An internal path string.

An absolute external URL (must be configured with [remotePatterns](#remotepatterns)).

A static import.

> **Good to know** : For security reasons, the Image Optimization API using the default [loader](#loader) will  *not*  forward headers when fetching the `src` image.
> If the `src` image requires authentication, consider using the [unoptimized](#unoptimized) property to disable Image Optimization.

###### `alt`

The `alt` property is used to describe the image for screen readers and search engines. It is also the fallback text if images have been disabled or an error occurs while loading the image.

It should contain text that could replace the image [without changing the meaning of the page](https://html.spec.whatwg.org/multipage/images.html#general-guidelines). It is not meant to supplement the image and should not repeat information that is already provided in the captions above or below the image.

If the image is [purely decorative](https://html.spec.whatwg.org/multipage/images.html#a-purely-decorative-image-that-doesn't-add-any-information) or [not intended for the user](https://html.spec.whatwg.org/multipage/images.html#an-image-not-intended-for-the-user), the `alt` property should be an empty string (`alt=""`).

> Learn more about [image accessibility guidelines](https://html.spec.whatwg.org/multipage/images.html#alt).

###### `width` and `height`

The `width` and `height` properties represent the [intrinsic](https://developer.mozilla.org/en-US/docs/Glossary/Intrinsic_Size) image size in pixels. This property is used to infer the correct  **aspect ratio**  used by browsers to reserve space for the image and avoid layout shift during loading. It does not determine the  *rendered size*  of the image, which is controlled by CSS.

You  **must**  set both `width` and `height` properties unless:

- The image is statically imported.

- The image has the [`fill` property](#fill)

If the height and width are unknown, we recommend using the [`fill` property](#fill).

###### `fill`

A boolean that causes the image to expand to the size of the parent element.

 **Positioning** :

- The parent element  **must**  assign `position: "relative"`, `"fixed"`, `"absolute"`.

- By default, the `<img>` element uses `position: "absolute"`.

 **Object Fit** :

If no styles are applied to the image, the image will stretch to fit the container. You can use `objectFit` to control cropping and scaling.

- `"contain"`: The image will be scaled down to fit the container and preserve aspect ratio.

- `"cover"`: The image will fill the container and be cropped.

> Learn more about [`position`](https://developer.mozilla.org/en-US/docs/Web/CSS/position) and [`object-fit`](https://developer.mozilla.org/docs/Web/CSS/object-fit).

###### `loader`

A custom function used to generate the image URL. The function receives the following parameters, and returns a URL string for the image:

- [`src`](#src)

- [`width`](#width-and-height)

- [`quality`](#quality)

> **Good to know** : Using props like `onLoad`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.

Alternatively, you can use the [loaderFile](#loaderfile) configuration in `next.config.js` to configure every instance of `next/image` in your application, without passing a prop.

###### `sizes`

Define the sizes of the image at different breakpoints. Used by the browser to choose the most appropriate size from the generated `srcset`.

`sizes` should be used when:

- The image is using the [`fill`](#fill) prop

- CSS is used to make the image responsive

If `sizes` is missing, the browser assumes the image will be as wide as the viewport (`100vw`). This can cause unnecessarily large images to be downloaded.

In addition, `sizes` affects how `srcset` is generated:

- Without `sizes`: Next.js generates a limited `srcset` (e.g. 1x, 2x), suitable for fixed-size images.

- With `sizes`: Next.js generates a full `srcset` (e.g. 640w, 750w, etc.), optimized for responsive layouts.

> Learn more about `srcset` and `sizes` on [web.dev](https://web.dev/learn/design/responsive-images/#sizes) and [mdn](https://developer.mozilla.org/docs/Web/HTML/Element/img#sizes).

###### `quality`

An integer between `1` and `100` that sets the quality of the optimized image. Higher values increase file size and visual fidelity. Lower values reduce file size but may affect sharpness.

If you’ve configured [qualities](#qualities) in `next.config.js`, the value must match one of the allowed entries.

> **Good to know** : If the original image is already low quality, setting a high quality value will increase the file size without improving appearance.

###### `style`

Allows passing CSS styles to the underlying image element.

> **Good to know** : If you’re using the `style` prop to set a custom width, be sure to also set `height: 'auto'` to preserve the image’s aspect ratio.

###### `preload`

A boolean that indicates if the image should be preloaded.

- `true`: [Preloads](https://web.dev/preload-responsive-images/) the image by inserting a `<link>` in the `<head>`.

- `false`: Does not preload the image.

 **When to use it:**

- The image is the [Largest Contentful Paint (LCP)](https://nextjs.org/learn/seo/web-performance/lcp) element.

- The image is above the fold, typically the hero image.

- You want to begin loading the image in the `<head>`, before its discovered later in the `<body>`.

 **When not to use it:**

- When you have multiple images that could be considered the [Largest Contentful Paint (LCP)](https://nextjs.org/learn/seo/web-performance/lcp) element depending on the viewport.

- When the `loading` property is used.

- When the `fetchPriority` property is used.

In most cases, you should use `loading="eager"` or `fetchPriority="high"` instead of `preload`.

###### `priority`

Starting with Next.js 16, the `priority` property has been deprecated in favor of the [`preload`](#preload) property in order to make the behavior clear.

###### `loading`

Controls when the image should start loading.

- `lazy`: Defer loading the image until it reaches a calculated distance from the viewport.

- `eager`: Load the image immediately, regardless of its position in the page.

Use `eager` only when you want to ensure the image is loaded immediately.

> Learn more about the [`loading` attribute](https://developer.mozilla.org/docs/Web/HTML/Element/img#loading).

###### `placeholder`

Specifies a placeholder to use while the image is loading, improving the perceived loading performance.

- `empty`: No placeholder while the image is loading.

- `blur`: Use a blurred version of the image as a placeholder. Must be used with the [`blurDataURL`](#blurdataurl) property.

- `data:image/...`: Uses the [Data URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) as the placeholder.

 **Examples:**

- [`blur` placeholder](https://image-component.nextjs.gallery/placeholder)

- [Shimmer effect with data URL `placeholder` prop](https://image-component.nextjs.gallery/shimmer)

- [Color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color)

> Learn more about the [`placeholder` attribute](https://developer.mozilla.org/docs/Web/HTML/Element/img#placeholder).

###### `blurDataURL`

A [Data URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) to
be used as a placeholder image before the image successfully loads. Can be automatically set or used with the [`placeholder="blur"`](#placeholder) property.

The image is automatically enlarged and blurred, so a very small image (10px or less) is recommended.

 **Automatic**

If `src` is a static import of a `jpg`, `png`, `webp`, or `avif` file, `blurDataURL` is added automatically—unless the image is animated.

 **Manually set**

If the image is dynamic or remote, you must provide `blurDataURL` yourself. To generate one, you can use:

- [A online tool like png-pixel.com](https://png-pixel.com)

- [A library like Plaiceholder](https://github.com/joe-bell/plaiceholder)

A large blurDataURL may hurt performance. Keep it small and simple.

 **Examples:**

- [Default `blurDataURL` prop](https://image-component.nextjs.gallery/placeholder)

- [Color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color)

###### `onLoad`

A callback function that is invoked once the image is completely loaded and the [placeholder](#placeholder) has been removed.

The callback function will be called with one argument, the event which has a `target` that references the underlying `<img>` element.

> **Good to know** : Using props like `onLoad`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.

###### `onError`

A callback function that is invoked if the image fails to load.

> **Good to know** : Using props like `onError`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.

###### `unoptimized`

A boolean that indicates if the image should be optimized. This is useful for images that do not benefit from optimization such as small images (less than 1KB), vector images (SVG), or animated images (GIF).

- `true`: The source image will be served as-is from the `src` instead of changing quality, size, or format.

- `false`: The source image will be optimized.

Since Next.js 12.3.0, this prop can be assigned to all images by updating `next.config.js` with the following configuration:

next.config.js

###### `overrideSrc`

When providing the `src` prop to the `<Image>` component, both the `srcset` and `src` attributes are generated automatically for the resulting `<img>`.

input.js
output.html

In some cases, it is not desirable to have the `src` attribute generated and you may wish to override it using the `overrideSrc` prop.

For example, when upgrading an existing website from `<img>` to `<Image>`, you may wish to maintain the same `src` attribute for SEO purposes such as image ranking or avoiding recrawl.

input.js
output.html

###### `decoding`

A hint to the browser indicating if it should wait for the image to be decoded before presenting other content updates or not.

- `async`: Asynchronously decode the image and allow other content to be rendered before it completes.

- `sync`: Synchronously decode the image for atomic presentation with other content.

- `auto`: No preference. The browser chooses the best approach.

> Learn more about the [`decoding` attribute](https://developer.mozilla.org/docs/Web/HTML/Element/img#decoding).

###### Other Props

Other properties on the `<Image />` component will be passed to the underlying `img` element with the exception of the following:

- `srcSet`: Use [Device Sizes](#devicesizes) instead.

###### Deprecated props

###### `onLoadingComplete`

> **Warning** : Deprecated in Next.js 14, use [`onLoad`](#onload) instead.

A callback function that is invoked once the image is completely loaded and the [placeholder](#placeholder) has been removed.

The callback function will be called with one argument, a reference to the underlying `<img>` element.

> **Good to know** : Using props like `onLoadingComplete`, which accept a function, requires using [Client Components](https://react.dev/reference/rsc/use-client) to serialize the provided function.

###### Configuration options

You can configure the Image Component in `next.config.js`. The following options are available:

###### `localPatterns`

Use `localPatterns` in your `next.config.js` file to allow images from specific local paths to be optimized and block all others.

next.config.js

The example above will ensure the `src` property of `next/image` must start with `/assets/images/` and must not have a query string. Attempting to optimize any other path will respond with `400` Bad Request error.

> **Good to know** : Omitting the `search` property allows all search parameters which could allow malicious actors to optimize URLs you did not intend. Try using a specific value like `search: '?v=2'` to ensure an exact match.

###### `remotePatterns`

Use `remotePatterns` in your `next.config.js` file to allow images from specific external paths and block all others. This ensures that only external images from your account can be served.

next.config.js

You can also configure `remotePatterns` using the object:

next.config.js

The example above will ensure the `src` property of `next/image` must start with `https://example.com/account123/` and must not have a query string. Any other protocol, hostname, port, or unmatched path will respond with `400` Bad Request.

 **Wildcard Patterns:**

Wildcard patterns can be used for both `pathname` and `hostname` and have the following syntax:

- `*` match a single path segment or subdomain

- `**` match any number of path segments at the end or subdomains at the beginning. This syntax does not work in the middle of the pattern.

next.config.js

This allows subdomains like `image.example.com`. Query strings and custom ports are still blocked.

> **Good to know** : When omitting `protocol`, `port`, `pathname`, or `search` then the wildcard `**` is implied. This is not recommended because it may allow malicious actors to optimize urls you did not intend.

 **Query Strings** :

You can also restrict query strings using the `search` property:

next.config.js

The example above will ensure the `src` property of `next/image` must start with `https://assets.example.com` and must have the exact query string `?v=1727111025337`. Any other protocol or query string will respond with `400` Bad Request.

Note that any allowed `remotePatterns` that respond with a redirect will follow the redirect from the remote image server without validating `remotePatterns` again on the redirect location. You can reduce or disable redirects by configuring [maximumRedirects](#maximumredirects).

###### `loaderFile`

`loaderFiles` allows you to use a custom image optimization service instead of Next.js.

next.config.js

The path must be relative to the project root. The file must export a default function that returns a URL string:

my/image/loader.js

 **Example:**

- [Custom Image Loader Configuration](/docs/app/api-reference/config/next-config-js/images#example-loader-configuration)

> Alternatively, you can use the [`loader` prop](#loader) to configure each instance of `next/image`.

###### `path`

If you want to change or prefix the default path for the Image Optimization API, you can do so with the `path` property. The default value for `path` is `/_next/image`.

next.config.js

###### `deviceSizes`

`deviceSizes` allows you to specify a list of device width breakpoints. These widths are used when the `next/image` component uses [`sizes`](#sizes) prop to ensure the correct image is served for the user's device.

If no configuration is provided, the default below is used:

next.config.js

###### `imageSizes`

`imageSizes` allows you to specify a list of image widths. These widths are concatenated with the array of [device sizes](#devicesizes) to form the full array of sizes used to generate image [srcset](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/srcset).

If no configuration is provided, the default below is used:

next.config.js

`imageSizes` is only used for images which provide a [`sizes`](#sizes) prop, which indicates that the image is less than the full width of the screen. Therefore, the sizes in `imageSizes` should all be smaller than the smallest size in `deviceSizes`.

###### `qualities`

`qualities` allows you to specify a list of image quality values.

If not configuration is provided, the default below is used:

next.config.js

> **Good to know** : This field is required starting with Next.js 16 because unrestricted access could allow malicious actors to optimize more qualities than you intended.

You can add more image qualities to the allowlist, such as the following:

next.config.js

In the example above, only four qualities are allowed: 25, 50, 75, and 100.

If the [`quality`](#quality) prop does not match a value in this array, the closest allowed value will be used.

If the REST API is visited directly with a quality that does not match a value in this array, the server will return a 400 Bad Request response.

###### `formats`

`formats` allows you to specify a list of image formats to be used.

next.config.js

Next.js automatically detects the browser's supported image formats via the request's `Accept` header in order to determine the best output format.

If the `Accept` header matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match (or the source image is animated), it will use the original image's format.

You can enable AVIF support, which will fallback to the original format of the src image if the browser [does not support AVIF](https://caniuse.com/avif):

next.config.js

You can also enable both AVIF and WebP formats together. AVIF will be preferred for browsers that support it, with WebP as a fallback:

next.config.js

> **Good to know** :
>
>
>
>
>
>
> - We still recommend using WebP for most use cases.
>
> - AVIF generally takes 50% longer to encode but it compresses 20% smaller compared to WebP. This means that the first time an image is requested, it will typically be slower, but subsequent requests that are cached will be faster.
>
> - When using multiple formats, Next.js will cache each format separately. This means increased storage requirements compared to using a single format, as both AVIF and WebP versions of images will be stored for different browser support.
>
> - If you self-host with a Proxy/CDN in front of Next.js, you must configure the Proxy to forward the `Accept` header.

###### `minimumCacheTTL`

`minimumCacheTTL` allows you to configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a [Static Image Import](/docs/app/getting-started/images#local-images) which will automatically hash the file contents and cache the image forever with a `Cache-Control` header of `immutable`.

If no configuration is provided, the default below is used.

next.config.js

You can increase the TTL to reduce the number of revalidations and potentially lower cost:

next.config.js

The expiration (or rather Max Age) of the optimized image is defined by either the `minimumCacheTTL` or the upstream image `Cache-Control` header, whichever is larger.

If you need to change the caching behavior per image, you can configure [`headers`](/docs/app/api-reference/config/next-config-js/headers) to set the `Cache-Control` header on the upstream image (e.g. `/some-asset.jpg`, not `/_next/image` itself).

There is no mechanism to invalidate the cache at this time, so its best to keep `minimumCacheTTL` low. Otherwise you may need to manually change the [`src`](#src) prop or delete the cached file `<distDir>/cache/images`.

###### `disableStaticImages`

`disableStaticImages` allows you to disable static image imports.

The default behavior allows you to import static files such as `import icon from './icon.png'` and then pass that to the `src` property. In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.

You can disable static image imports inside your `next.config.js`:

next.config.js

###### `maximumRedirects`

The default image optimization loader will follow HTTP redirects when fetching remote images up to 3 times.

next.config.js

For your convenience, these redirects do not need to satisfy [remotePatterns](#remotepatterns).

You can configure the number of redirects to follow when fetching remote images. Setting the value to `0` will disable following redirects.

next.config.js

###### `maximumDiskCacheSize`

The default image optimization loader will write optimized images to disk so subsequent requests can be served faster from the disk cache.

You can configure the maximum disk cache size in bytes, for example 500 MB:

next.config.js

You can also disable the disk cache entirely by setting the value to `0`.

next.config.js

If no value is configured, the default behavior is to check the current available disk space once during startup and use 50%.

When the disk cache exceeds the configured size, the least recently used optimized images will be deleted until the cache is under the limit again.

Alternatively, you can implement your own cache handler using [`cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) which will ignore the `maximumDiskCacheSize` configuration.

###### `maximumResponseBody`

The default image optimization loader will fetch source images up to 50 MB in size.

next.config.js

If you know all your source images are small, you can protect memory constrained servers by reducing this to a smaller value such as 5 MB.

next.config.js

###### `dangerouslyAllowLocalIP`

In rare cases when self-hosting Next.js on a private network, you may want to allow optimizing images from local IP addresses on the same network. This is not recommended for most users because it could allow malicious users to access content on your internal network.

By default, the value is false.

next.config.js

If you need to optimize remote images hosted elsewhere in your local network, you can set the value to true.

next.config.js

This might be necessary when hosting Next.js in a VPC with split-horizon DNS and you receive status 400 Bad Request. Only enable once you understand the SSRF risk.

###### `dangerouslyAllowSVG`

`dangerouslyAllowSVG` allows you to serve SVG images.

next.config.js

By default, Next.js does not optimize SVG images for a few reasons:

- SVG is a vector format meaning it can be resized losslessly.

- SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/app/api-reference/config/next-config-js/headers#content-security-policy).

We recommend using the [`unoptimized`](#unoptimized) prop when the [`src`](#src) prop is known to be SVG. This happens automatically when `src` ends with `".svg"`.

In addition, it is strongly recommended to also set `contentDispositionType` to force the browser to download the image, as well as `contentSecurityPolicy` to prevent scripts embedded in the image from executing.

next.config.js

###### `contentDispositionType`

`contentDispositionType` allows you to configure the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_response_header_for_the_main_body) header.

next.config.js

###### `contentSecurityPolicy`

`contentSecurityPolicy` allows you to configure the [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) header for images. This is particularly important when using [`dangerouslyAllowSVG`](#dangerouslyallowsvg) to prevent scripts embedded in the image from executing.

next.config.js

By default, the [loader](#loader) sets the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_response_header_for_the_main_body) header to `attachment` for added protection since the API can serve arbitrary remote images.

The default value is `attachment` which forces the browser to download the image when visiting directly. This is particularly important when [`dangerouslyAllowSVG`](#dangerouslyallowsvg) is true.

You can optionally configure `inline` to allow the browser to render the image when visiting directly, without downloading it.

###### Deprecated configuration options

###### `domains`

> **Warning** : Deprecated since Next.js 14 in favor of strict [`remotePatterns`](#remotepatterns) in order to protect your application from malicious users.

Similar to [`remotePatterns`](#remotepatterns), the `domains` configuration can be used to provide a list of allowed hostnames for external images. However, the `domains` configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname.

Since most remote image servers are shared between multiple tenants, it's safer to use `remotePatterns` to ensure only the intended images are optimized.

Below is an example of the `domains` property in the `next.config.js` file:

next.config.js

##### Functions

###### `getImageProps`

The `getImageProps` function can be used to get the props that would be passed to the underlying `<img>` element, and instead pass them to another component, style, canvas, etc.

This also avoid calling React `useState()` so it can lead to better performance, but it cannot be used with the [`placeholder`](#placeholder) prop because the placeholder will never be removed.

##### Known browser bugs

This `next/image` component uses browser native [lazy loading](https://caniuse.com/loading-lazy-attr), which may fallback to eager loading for older browsers before Safari 15.4. When using the blur-up placeholder, older browsers before Safari 12 will fallback to empty placeholder. When using styles with `width`/`height` of `auto`, it is possible to cause [Layout Shift](https://web.dev/cls/) on older browsers before Safari 15 that don't [preserve the aspect ratio](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes). For more details, see [this MDN video](https://www.youtube.com/watch?v=4-d_SoCHeWE).

- [Safari 15 - 16.3](https://bugs.webkit.org/show_bug.cgi?id=243601) display a gray border while loading. Safari 16.4 [fixed this issue](https://webkit.org/blog/13966/webkit-features-in-safari-16-4/#:~:text=Now%20in%20Safari%2016.4%2C%20a%20gray%20line%20no%20longer%20appears%20to%20mark%20the%20space%20where%20a%20lazy%2Dloaded%20image%20will%20appear%20once%20it%E2%80%99s%20been%20loaded.). Possible solutions:

- Use CSS `@supports (font: -apple-system-body) and (-webkit-appearance: none) { img[loading="lazy"] { clip-path: inset(0.6px) } }`

- Use [`loading="eager"`](#loading) if the image is above the fold

- [Firefox 67+](https://bugzilla.mozilla.org/show_bug.cgi?id=1556156) displays a white background while loading. Possible solutions:

- Enable [AVIF `formats`](#formats)

- Use [`placeholder`](#placeholder)

##### Examples

###### Styling images

Styling the Image component is similar to styling a normal `<img>` element, but there are a few guidelines to keep in mind:

Use `className` or `style`, not `styled-jsx`. In most cases, we recommend using the `className` prop. This can be an imported [CSS Module](/docs/app/getting-started/css), a [global stylesheet](/docs/app/getting-started/css#global-css), etc.

You can also use the `style` prop to assign inline styles.

When using `fill`, the parent element must have `position: relative` or `display: block`. This is necessary for the proper rendering of the image element in that layout mode.

You cannot use [styled-jsx](/docs/app/guides/css-in-js) because it's scoped to the current component (unless you mark the style as `global`).

###### Responsive images with a static export

When you import a static image, Next.js automatically sets its width and height based on the file. You can make the image responsive by setting the style:

<img src="/_next/image?

import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="/profile.png"
      width={500}
      height={500}
      alt="Picture of the author"
    />
  )
}

import profile from './profile.png'

export default function Page() {
  return <Image src={profile} />
}

<Image src="/profile.png" width={500} height={500} />

<Image src="/profile.png" fill={true} />

'use client'

import Image from 'next/image'

const imageLoader = ({ src, width, quality }) => {
  return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}

export default function Page() {
  return (
    <Image
      loader={imageLoader}
      src="me.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

import Image from 'next/image'

export default function Page() {
  return (
    <div className="grid-element">
      <Image
        fill
        src="/example.png"
        sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
      />
    </div>
  )
}

// Default quality is 75
<Image quality={75} />

const imageStyle = {
  borderRadius: '50%',
  border: '1px solid #fff',
  width: '100px',
  height: 'auto',
}

export default function ProfileImage() {
  return <Image src="..." style={imageStyle} />
}

// Default preload is false
<Image preload={false} />

// Defaults to lazy
<Image loading="lazy" />

// defaults to empty
<Image placeholder="empty" />

<Image placeholder="blur" blurDataURL="..." />

<Image onLoad={(e) => console.log(e.target.naturalWidth)} />

<Image onError={(e) => console.error(e.target.id)} />

import Image from 'next/image'

const UnoptimizedImage = (props) => {
  // Default is false
  return <Image {...props} unoptimized />
}

module.exports = {
  images: {
    unoptimized: true,
  },
}

<img
  srcset="
    /_next/image?url=%2Fprofile.jpg&w=640&q=75 1x,
    /_next/image?url=%2Fprofile.jpg&w=828&q=75 2x
  "
  src="/_next/image?url=%2Fprofile.jpg&w=828&q=75"
/>

<Image src="/profile.jpg" overrideSrc="/override.jpg" />

<img
  srcset="
    /_next/image?url=%2Fprofile.jpg&w=640&q=75 1x,
    /_next/image?url=%2Fprofile.jpg&w=828&q=75 2x
  "
  src="/override.jpg"
/>

// Default is async
<Image decoding="async" />

'use client'

<Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />

module.exports = {
  images: {
    localPatterns: [
      {
        pathname: '/assets/images/**',
        search: '',
      },
    ],
  },
}

module.exports = {
  images: {
    remotePatterns: [new URL('https://example.com/account123/**')],
  },
}

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
        port: '',
        pathname: '/account123/**',
        search: '',
      },
    ],
  },
}

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.example.com',
        port: '',
        search: '',
      },
    ],
  },
}

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'assets.example.com',
        search: '?v=1727111025337',
      },
    ],
  },
}

module.exports = {
  images: {
    loader: 'custom',
    loaderFile: './my/image/loader.js',
  },
}

'use client'

export default function myImageLoader({ src, width, quality }) {
  return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}

module.exports = {
  images: {
    path: '/my-prefix/_next/image',
  },
}

module.exports = {
  images: {
    qualities: [75],
  },
}

module.exports = {
  images: {
    qualities: [25, 50, 75, 100],
  },
}

module.exports = {
  images: {
    // Default
    formats: ['image/webp'],
  },
}

module.exports = {
  images: {
    formats: ['image/avif'],
  },
}

module.exports = {
  images: {
    formats: ['image/avif', 'image/webp'],
  },
}

module.exports = {
  images: {
    minimumCacheTTL: 14400, // 4 hours
  },
}

module.exports = {
  images: {
    minimumCacheTTL: 2678400, // 31 days
  },
}

module.exports = {
  images: {
    disableStaticImages: true,
  },
}

module.exports = {
  images: {
    maximumRedirects: 3,
  },
}

module.exports = {
  images: {
    maximumRedirects: 0,
  },
}

module.exports = {
  images: {
    maximumDiskCacheSize: 500_000_000,
  },
}

module.exports = {
  images: {
    maximumDiskCacheSize: 0,
  },
}

module.exports = {
  images: {
    maximumResponseBody: 50_000_000,
  },
}

module.exports = {
  images: {
    maximumResponseBody: 5_000_000,
  },
}

module.exports = {
  images: {
    dangerouslyAllowLocalIP: false,
  },
}

module.exports = {
  images: {
    dangerouslyAllowLocalIP: true,
  },
}

module.exports = {
  images: {
    dangerouslyAllowSVG: true,
  },
}

<Image src="/my-image.svg" unoptimized />

module.exports = {
  images: {
    dangerouslyAllowSVG: true,
    contentDispositionType: 'attachment',
    contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },
}

module.exports = {
  images: {
    contentDispositionType: 'inline',
  },
}

module.exports = {
  images: {
    contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },
}

module.exports = {
  images: {
    domains: ['assets.acme.com'],
  },
}

import { getImageProps } from 'next/image'

const { props } = getImageProps({
  src: 'https://example.com/image.jpg',
  alt: 'A scenic mountain view',
  width: 1200,
  height: 800,
})

function ImageWithCaption() {
  return (
    <figure>
      <img {...props} />
      <figcaption>A scenic mountain view</figcaption>
    </figure>
  )
}

import styles from './styles.module.css'

export default function MyImage() {
  return <Image className={styles.image} src="/my-image.png" alt="My Image" />
}

export default function MyImage() {
  return (
    <Image style={{ borderRadius: '8px' }} src="/my-image.png" alt="My Image" />
  )
}

<Image fill src="/my-image.png" alt="My Image" />

import Image from 'next/image'
import mountains from '../public/mountains.jpg'

export default function Responsive() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <Image
        alt="Mountains"
        // Importing an image will
        // automatically set the width and height
        src={mountains}
        sizes="100vw"
        // Make the image display full width
        // and preserve its aspect ratio
        style={{
          width: '100%',
          height: 'auto',
        }}
      />
    </div>
  )
}

import Image from 'next/image'

export default function Page({ photoUrl }) {
  return (
    <Image
      src={photoUrl}
      alt="Picture of the author"
      sizes="100vw"
      style={{
        width: '100%',
        height: 'auto',
      }}
      width={500}
      height={300}
    />
  )
}

import Image from 'next/image'
import mountains from '../public/mountains.jpg'

export default function Fill() {
  return (
    <div
      style={{
        display: 'grid',
        gridGap: '8px',
        gridTemplateColumns: 'repeat(auto-fit, minmax(400px, auto))',
      }}
    >
      <div style={{ position: 'relative', width: '400px' }}>
        <Image
          alt="Mountains"
          src={mountains}
          fill
          sizes="(min-width: 808px) 50vw, 100vw"
          style={{
            objectFit: 'cover', // cover, contain, none
          }}
        />
      </div>
      {/* And more images in the grid... */}
    </div>
  )
}

import Image from 'next/image'
import mountains from '../public/mountains.jpg'

export default function Background() {
  return (
    <Image
      alt="Mountains"
      src={mountains}
      placeholder="blur"
      quality={100}
      fill
      sizes="100vw"
      style={{
        objectFit: 'cover',
      }}
    />
  )
}

import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="https://s3.amazonaws.com/my-bucket/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
        search: '',
      },
    ],
  },
}

.imgDark {
  display: none;
}

@media (prefers-color-scheme: dark) {
  .imgLight {
    display: none;
  }
  .imgDark {
    display: unset;
  }
}

import styles from './theme-image.module.css'
import Image, { ImageProps } from 'next/image'

type Props = Omit<ImageProps, 'src' | 'preload' | 'loading'> & {
  srcLight: string
  srcDark: string
}

const ThemeImage = (props: Props) => {
  const { srcLight, srcDark, ...rest } = props

  return (
    <>
      <Image {...rest} src={srcLight} className={styles.imgLight} />
      <Image {...rest} src={srcDark} className={styles.imgDark} />
    </>
  )
}

import { getImageProps } from 'next/image'

export default function Home() {
  const common = { alt: 'Art Direction Example', sizes: '100vw' }
  const {
    props: { srcSet: desktop },
  } = getImageProps({
    ...common,
    width: 1440,
    height: 875,
    quality: 80,
    src: '/desktop.jpg',
  })
  const {
    props: { srcSet: mobile, ...rest },
  } = getImageProps({
    ...common,
    width: 750,
    height: 1334,
    quality: 70,
    src: '/mobile.jpg',
  })

  return (
    <picture>
      <source media="(min-width: 1000px)" srcSet={desktop} />
      <source media="(min-width: 500px)" srcSet={mobile} />
      <img {...rest} style={{ width: '100%', height: 'auto' }} />
    </picture>
  )
}

import { getImageProps } from 'next/image'

function getBackgroundImage(srcSet = '') {
  const imageSet = srcSet
    .split(', ')
    .map((str) => {
      const [url, dpi] = str.split(' ')
      return `url("${url}") ${dpi}`
    })
    .join(', ')
  return `image-set(${imageSet})`
}

export default function Home() {
  const {
    props: { srcSet },
  } = getImageProps({ alt: '', width: 128, height: 128, src: '/img.png' })
  const backgroundImage = getBackgroundImage(srcSet)
  const style = { height: '100vh', width: '100vw', backgroundImage }

  return (

Hello World

  )
}


Link Component

Summary: This page documents the Next.js `<Link>` component, a React component that extends the HTML `<a>` element to provide prefetching and client-side navigation between routes. It covers the component's…

Link Component

`<Link>` is a React component that extends the HTML `<a>` element to provide [prefetching](/docs/app/getting-started/linking-and-navigating#prefetching) and client-side navigation between routes. It…

import Link from 'next/link'

export default function Page() {
  return <Link href="/dashboard">Dashboard</Link>
}

Reference

The following props can be passed to the `<Link>` component:

| Prop | Example | Type | Required |
| --- | --- | --- | --- |
| [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes…

href (required)

The path or URL to navigate to.

import Link from 'next/link'

// Navigate to /about?name=test
export default function Page() {
  return (
    <Link
      href={{
        pathname: '/about',
        query: { name: 'test' },…

replace

**Defaults to `false`.** When `true`, `next/link` will replace the current history state instead of adding a new URL into the [browser's…

import Link from 'next/link'

export default function Page() {
  return (
    <Link href="/dashboard" replace>
      Dashboard
    </Link>
  )
}

scroll

**Defaults to `true`.** The default scrolling behavior of `<Link>` in Next.js **is to maintain scroll position**, similar to how browsers handle back and forwards navigation. When you navigate to a…

import Link from 'next/link'

export default function Page() {
  return (
    <Link href="/dashboard" scroll={false}>
      Dashboard
    </Link>
  )
}

prefetch

Prefetching happens when a `<Link />` component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the `href`) and its data in the…

import Link from 'next/link'

export default function Page() {
  return (
    <Link href="/dashboard" prefetch={false}>
      Dashboard
    </Link>
  )
}

onNavigate

An event handler called during client-side navigation. The handler receives an event object that includes a `preventDefault()` method, allowing you to cancel the navigation if needed.

> **Good to…

import Link from 'next/link'

export default function Page() {
  return (
    <Link
      href="/dashboard"
      onNavigate={(e) => {
        // Only executes during SPA navigation…

transitionTypes

A list of transition types to apply to the navigation. These types are passed to [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType) inside the navigation transition,…

import Link from 'next/link'

export default function Page() {
  return (
    <Link href="/about" transitionTypes={['slide-in']}>
      About
    </Link>
  )
}

Examples

The following examples demonstrate how to use the `<Link>` component in different scenarios.

Linking to dynamic route segments

When linking to [dynamic segments](/docs/app/api-reference/file-conventions/dynamic-routes), you can use [template literals and…

import Link from 'next/link'

interface Post {
  id: number
  title: string
  slug: string
}

export default function PostList({ posts }: { posts: Post[] }) {
  return (
    <ul>…

Checking active links

You can use [`usePathname()`](/docs/app/api-reference/functions/use-pathname) to check if a link is active. For example, to add a class to the active link, you can check if the current `pathname`…

'use client'

import { usePathname } from 'next/navigation'
import Link from 'next/link'

export function Links() {
  const pathname = usePathname()

  return (
    <nav>
      <Link…

Scrolling to an `id`

If you'd like to scroll to a specific `id` on navigation, you can append your URL with a `#` hash link or just pass a hash link to the `href` prop. This is possible since `<Link>` renders to an `<a>`…

<Link href="/dashboard#settings">Settings</Link>

// Output
Settings

Replace the URL instead of push

The default behavior of the `Link` component is to `push` a new URL into the `history` stack. You can use the `replace` prop to prevent adding a new entry, as in the following example:

import Link from 'next/link'

export default function Page() {
  return (
    <Link href="/about" replace>
      About us
    </Link>
  )
}

Disable scrolling to the top of the page

The default scrolling behavior of `<Link>` in Next.js  **is to maintain scroll position**, similar to how browsers handle back and forwards navigation. When you navigate to a new…

import Link from 'next/link'

export default function Page() {
  return (
    <Link href="/#hashid" scroll={false}>
      Disables scrolling to the top
    </Link>
  )
}

// useRouter
import { useRouter } from 'next/navigation'

const router = useRouter()

router.push('/dashboard', { scroll: false })

Scroll offset with sticky headers

Because Next.js skips sticky and fixed positioned elements when finding the scroll target, content may end up behind a sticky header after navigation. For example, if your layout has a sticky…

import './globals.css'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        <header className="sticky top-0…

html {
  scroll-padding-top: 64px; /* Match the height of your sticky header */
}

Prefetching links in Proxy

It's common to use [Proxy](/docs/app/api-reference/file-conventions/proxy) for authentication or other purposes that involve rewriting the user to a different page. In order for the `<Link />`…

import { NextResponse } from 'next/server'

export function proxy(request: Request) {
  const nextUrl = request.nextUrl
  if (nextUrl.pathname === '/dashboard') {
    if (request.cookies.authToken)…

'use client'

import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook

export default function Page() {
  const isAuthed = useIsAuthed()
  const path = isAuthed…

Blocking navigation

You can use the `onNavigate` prop to block navigation when certain conditions are met, such as when a form has unsaved changes. When you need to block navigation across multiple components in your…

'use client'

import { createContext, useState, useContext } from 'react'

interface NavigationBlockerContextType {
  isBlocked: boolean
  setIsBlocked: (isBlocked: boolean) => void
}

export…

'use client'

import { useNavigationBlocker } from '../contexts/navigation-blocker'

export default function Form() {
  const { setIsBlocked } = useNavigationBlocker()

  return (
    <form…

'use client'

import Link from 'next/link'
import { useNavigationBlocker } from '../contexts/navigation-blocker'

interface CustomLinkProps extends React.ComponentProps<typeof Link> {
  children:…

'use client'

import { CustomLink as Link } from './custom-link'

export default function Nav() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>…

import { NavigationBlockerProvider } from './contexts/navigation-blocker'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">…

import Nav from './components/nav'
import Form from './components/form'

export default function Page() {
  return (

Welcome to the Dashboard
…

Version history

| Version | Changes |
| --- | --- |
| `v16.2.0` | Add `transitionTypes` prop. |
| `v15.4.0` | Add `auto` as an alias to the default `prefetch` behavior. |
| `v15.3.0` | Add `onNavigate` API |
|…

href

The path or URL to navigate to.

replace

When `true`, `next/link` will replace the current history state instead of adding a new URL into the browser's history stack.

scroll

The default scrolling behavior of `<Link>` in Next.js is to maintain scroll position. When `scroll={false}`, Next.js will not attempt to scroll to the first Page element.

prefetch

Prefetch behavior depends on whether the route is static or dynamic. When `true`, the full route is prefetched. When `false`, prefetching never happens. When `null` or `'auto'`, the default behavior…

transitionTypes

A list of transition types to apply to the navigation. These types are passed to `React.addTransitionType` inside the navigation transition, enabling `<ViewTransition>` components to apply different…