metadata
dict
url
stringlengths
19
103
markdown
stringlengths
199
68.6k
{ "contentLength": null, "etag": "W/\"9f3003ae728d71a7a89fbdc42395889c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [What is Next.js?](#what-is-nextjs) * [Main Features](#main-features) * [How to Use These Docs](#how-to-use-these-docs) * [App Router vs Pages Router](#app-router-vs-pages-router) * [Pre-Requisite Knowledge](#pre-requisite-knowledge) * [Accessibility](#accessibility) * [Join our Community](#join-our-community) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top Introduction ============ Welcome to the Next.js documentation! [What is Next.js?](#what-is-nextjs) ----------------------------------- 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. Under the hood, Next.js also abstracts and automatically configures tooling needed for React, like bundling, compiling, and more. This allows you to focus on building your application instead of spending time with configuration. Whether you're an individual developer or part of a larger team, Next.js can help you build interactive, dynamic, and fast React applications. [Main Features](#main-features) ------------------------------- Some of the main Next.js features include: Feature Description [Routing](/docs/app/building-your-application/routing) A file-system based router built on top of Server Components that supports layouts, nested routing, loading states, error handling, and more. [Rendering](/docs/app/building-your-application/rendering) Client-side and Server-side Rendering with Client and Server Components. Further optimized with Static and Dynamic Rendering on the server with Next.js. Streaming on Edge and Node.js runtimes. [Data Fetching](/docs/app/building-your-application/data-fetching) Simplified data fetching with async/await in Server Components, and an extended `fetch` API for request memoization, data caching and revalidation. [Styling](/docs/app/building-your-application/styling) Support for your preferred styling methods, including CSS Modules, Tailwind CSS, and CSS-in-JS [Optimizations](/docs/app/building-your-application/optimizing) Image, Fonts, and Script Optimizations to improve your application's Core Web Vitals and User Experience. [TypeScript](/docs/app/building-your-application/configuring/typescript) Improved support for TypeScript, with better type checking and more efficient compilation, as well as custom TypeScript Plugin and type checker. [How to Use These Docs](#how-to-use-these-docs) ----------------------------------------------- On the left side of the screen, you'll find the docs navbar. The pages of the docs are organized sequentially, from basic to advanced, so you can follow them step-by-step when building your application. However, you can read them in any order or skip to the pages that apply to your use case. On the right side of the screen, you'll see a table of contents that makes it easier to navigate between sections of a page. If you need to quickly find a page, you can use the search bar at the top, or the search shortcut (`Ctrl+K` or `Cmd+K`). To get started, checkout the [Installation](/docs/getting-started/installation) guide. [App Router vs Pages Router](#app-router-vs-pages-router) --------------------------------------------------------- Next.js has two different routers: the App Router and the Pages Router. The App Router is a newer router that allows you to use React's latest features, such as Server Components and Streaming. The Pages Router is the original Next.js router, which allowed you to build server-rendered React applications and continues to be supported for older Next.js applications. At the top of the sidebar, you'll notice a dropdown menu that allows you to switch between the **App Router** and the **Pages Router** features. Since there are features that are unique to each directory, it's important to keep track of which tab is selected. The breadcrumbs at the top of the page will also indicate whether you're viewing App Router docs or Pages Router docs. [Pre-Requisite Knowledge](#pre-requisite-knowledge) --------------------------------------------------- Although our docs are designed to be beginner-friendly, we need to establish a baseline so that the docs can stay focused on Next.js functionality. We'll make sure to provide links to relevant documentation whenever we introduce a new concept. To get the most out of our docs, it's recommended that you have a basic understanding of HTML, CSS, and React. If you need to brush up on your React skills, check out our [React Foundations Course](/learn/react-foundations), which will introduce you to the fundamentals. Then, learn more about Next.js by [building a dashboard application](/learn/dashboard-app). [Accessibility](#accessibility) ------------------------------- For optimal accessibility when using a screen reader while reading the docs, we recommend using Firefox and NVDA, or Safari and VoiceOver. [Join our Community](#join-our-community) ----------------------------------------- If you have questions about anything related to Next.js, you're always welcome to ask our community on [GitHub Discussions](https://github.com/vercel/next.js/discussions), [Discord](https://discord.com/invite/bUG2bvbtHy), [Twitter](https://twitter.com/nextjs), and [Reddit](https://www.reddit.com/r/nextjs). [ ### Getting Started Learn how to create full-stack web applications with Next.js. ](/docs/getting-started)[ ### App Router Use the new App Router with Next.js' and React's latest features, including Layouts, Server Components, Suspense, and more. ](/docs/app)[ ### Pages Router Before Next.js 13, the Pages Router was the main way to create routes in Next.js with an intuitive file-system router. ](/docs/pages)[ ### Architecture How Next.js Works ](/docs/architecture)[ ### Community Get involved in the Next.js community. ](/docs/community) [Next Installation ](/docs/getting-started/installation) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"45288f403da6b7279bc5a994262ee748\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/showcase
ran **May 23**. Check out the announcements. Vercel Ship 24 [Watch the Keynote](https://vercel.com/ship?utm_source=next_site&utm_medium=web&utm_campaign=vercel_ship&utm_content=next_site_showcase) Vercel Ship 24 ran **May 23**. Check out the announcements. [Watch the Keynote](https://vercel.com/ship?utm_source=next_site&utm_medium=web&utm_campaign=vercel_ship&utm_content=next_site_showcase) The web framework for when it mattersself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rij6unhn6uf:",1) ======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================= Peerless performance, efficiency and developer experience. Next.js is trusted by some of the biggest names of the web.self.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":R1qj6unhn6uf:",1)Peerless performance, efficiency and developer experienceself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":R2qj6unhn6uf:",1) [Learn About Managed Next.js](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=showcase_redesign&utm_campaign=hero_cta)[Contact Sales](https://vercel.com/contact/sales/nextjs?utm_source=next_site&utm_medium=showcase_redesign&utm_campaign=hero_cta) * ![Washington Post article](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1675140153%2Fnextjs%2Fshowcase%2Fwapo.jpg&w=1920&q=75) ![the Washington Post logo](https://assets.vercel.com/image/upload/v1675111868/nextjs/showcase/wapost.svg) [Read the Washington Post's customer story](https://vercel.com/customers/washington-post-next.js-vercel-engineering-at-the-speed-of-breaking-news?utm_source=next-site&utm_medium=showcase-wapost-card&utm_campaign=showcase-new) ![the Washington Post logo](https://assets.vercel.com/image/upload/v1675111868/nextjs/showcase/wapost.svg) Engineering a site at the speed of breaking newsself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rl8b36unhn6uf:",1)The Washington Post had 5 billion+ AWS Lambda invocations per week, and saw lightning-fast turnaround on developing new features. 5 Billion+ Lambda invocations per week Lighting-Fast Turnaround on developing new features [Read the customer story](https://vercel.com/customers/washington-post-next.js-vercel-engineering-at-the-speed-of-breaking-news?utm_source=next-site&utm_medium=showcase-wapost-card&utm_campaign=showcase-new) 5 Billion+ Lambda invocations per week Lighting-Fast Turnaround on developing new features * ![](/_next/static/media/template-grid.d2964a3f.svg) ![](/_next/static/media/chatbot-visual.f9712721.svg) [View the AI Chatbot Template template](https://vercel.com/templates/next.js/nextjs-ai-chatbot?utm_source=next-site&utm_medium=showcase-ai-chatbot-card&utm_campaign=showcase-new) AI Chatbot Template A full-featured, hackable Next.js AI chatbot built by Vercelself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rl8j36unhn6uf:",1) [Deploy this template](https://vercel.com/templates/next.js/nextjs-ai-chatbot?utm_source=next-site&utm_medium=showcase-ai-chatbot-card&utm_campaign=showcase-new) * ![](/_next/static/media/stripe-visual.abb7a693.svg) ![Stripe logo](https://assets.vercel.com/image/upload/v1675111868/nextjs/showcase/stripe.svg) [Read Stripe's customer story](https://vercel.com/blog/architecting-reliability-stripes-black-friday-site?utm_source=next-site&utm_medium=showcase-stripe-card&utm_campaign=showcase-new) ![Stripe logo](https://assets.vercel.com/image/upload/v1675111868/nextjs/showcase/stripe.svg) Architecting a live look at reliability: Stripe's viral Black Friday siteself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rl8r36unhn6uf:",1)With Vercel, Stripe's Black Friday site saw 100% uptime with over 17 million edge requests at launch 100% Uptime 17m+ Edge requests at launch [Read the customer story](https://vercel.com/blog/architecting-reliability-stripes-black-friday-site?utm_source=next-site&utm_medium=showcase-stripe-card&utm_campaign=showcase-new) 100% Uptime 17m+ Edge requests at launch * ![](/_next/static/media/sonos-visual.371c925c.svg) ![Sonos logo](https://assets.vercel.com/image/upload/v1675111868/nextjs/showcase/sonos.svg) [Read Sonos's customer story](https://vercel.com/blog/how-sonos-amplified-their-devex?utm_source=next-site&utm_medium=showcase-sonos-card&utm_campaign=showcase-new) ![Sonos logo](https://assets.vercel.com/image/upload/v1675111868/nextjs/showcase/sonos.svg) Developing at the speed of sound: How Sonos amplified their DevExself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rl9336unhn6uf:",1)After migrating to Next.js and Vercel, Sonos had 75% faster build times and improved their performance scores by 10% 75% faster Build times 10% better Performance scores [Read the customer story](https://vercel.com/blog/how-sonos-amplified-their-devex?utm_source=next-site&utm_medium=showcase-sonos-card&utm_campaign=showcase-new) 75% faster Build times 10% better Performance scores * ![](/_next/static/media/template-grid.d2964a3f.svg) ![](/_next/static/media/commerce-visual.163d1fa7.svg) [View the Commerce Template template](https://vercel.com/templates/next.js/nextjs-commerce?utm_source=next-site&utm_medium=showcase-commerce-template-card&utm_campaign=showcase-new) Commerce Template Starter kit for high-performance commerce with Shopifyself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rl9b36unhn6uf:",1) [Deploy this template](https://vercel.com/templates/next.js/nextjs-commerce?utm_source=next-site&utm_medium=showcase-commerce-template-card&utm_campaign=showcase-new) 14th   Largest on GitHub \# 1 React Framework 110,000 Stars on GitHub Meet thousands of beautiful websites built with Next.js by Vercelself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rn6unhn6uf:",1) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- All Composable Commerce Web Apps AI Marketing & Media Platform Engineering [ ![](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fsonos.fd388bcb.png&w=750&q=55) Sonos Composable Commerce ](https://vercel.com/blog/how-sonos-amplified-their-devex?utm_source=next-site&utm_medium=sonos_callout&utm_campaign=showcase-new)[ ![](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fnike.509ec268.jpg&w=750&q=55) Nike Composable Commerce ](https://www.nike.com)[ ![](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fchatgpt.c6245dc6.png&w=750&q=55) OpenAI ChatGPT AI ](https://chatgpt.com/)[ ![](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fclaude.5aa10087.png&w=750&q=55) Claude AI ](https://claude.ai/)[ ![](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fspotify.6415e03a.png&w=750&q=55) Spotify Web Apps ](https://open.spotify.com)[ ![](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fnerdwallet.d4dd8d82.png&w=750&q=55) NerdWallet Web Apps ](https://www.nerdwallet.com/) Load More Powering the best frontend teams ![Sonos Logo](https://assets.vercel.com/image/upload/v1582596549/front/home/new/logos/sonos.svg) ![Spotify Logo](https://assets.vercel.com/image/upload/v1711718485/front/home/new/logos/spotify.svg) ![OpenAI Logo](https://assets.vercel.com/image/upload/v1675298561/front/home/new/logos/open-ai.svg) ![twitch Logo](https://assets.vercel.com/image/upload/v1675298561/front/home/new/logos/twitch.svg) ![Patreon Logo](https://assets.vercel.com/image/upload/v1618004238/front/home/new/logos/patreon.svg) ![Auth0 Logo](https://assets.vercel.com/image/upload/v1581706075/front/home/new/logos/auth0.svg) ![IMDB Logo](https://assets.vercel.com/image/upload/v1711718484/front/home/new/logos/imdb.svg) StarterEcommerceBlogAIEdge FunctionsEdge ConfigPortfolioSaaSMulti-tenant AppsRealtime AppsDocumentationVirtual EventWeb3 Build like the Best ------------------- Jumpstart your Next.js development with pre-built solutions from Vercel and our community.self.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":R9j96unhn6uf:",1) [Deploy a Template on Vercel](https://vercel.com/templates/next.js?utm_source=next-site&utm_medium=deploy-template-on-vercel-cta&utm_campaign=showcase-new) ![A Next.js app and a Serverless Function API.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122002%2Fnextjs%2Fshowcase%2Ftemplate-next-boilerplate.jpg&w=3840&q=75) Next.js Boilerplate A Next.js app and a Serverless Function API. ![An image gallery built on Next.js and Cloudinary.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122387%2Fnextjs%2Fshowcase%2Ftemplate-next-gallery.jpg&w=3840&q=75) Image Gallery Starter An image gallery built on Next.js and Cloudinary. ![An all-in-one starter kit for high-performance ecommerce sites.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122003%2Fnextjs%2Fshowcase%2Ftemplate-next-commerce.jpg&w=3840&q=75) Next.js Commerce An all-in-one starter kit for high-performance ecommerce sites. A powerful framework for building high-performance, server rendered web applicationsself.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":Rr6unhn6uf:",0.23) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### Superior Developer Experience Deploy your Next.js site globally in seconds, with zero configuration just Git push to get started.self.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":R2jb6unhn6uf:",1) ### Battle-tested in Production All the features you need for production: hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more.self.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":R2lb6unhn6uf:",1) ### Performance-obsessed stack Next.js brings years of experience in building and optimizing production applications.self.\_\_wrap\_n=self.\_\_wrap\_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.\_\_wrap\_b=(e,t,s)=>{let r=(s=s||document.querySelector(\`\[data-br="${e}"\]\`)).parentElement,n=e=>s.style.maxWidth=e+"px";s.style.maxWidth="";let a=r.clientWidth,i=r.clientHeight,c=a/2-.25,l=a+.5,o;if(a){for(n(c),c=Math.max(s.scrollWidth,c);c+1<l;)n(o=Math.round((c+l)/2)),r.clientHeight===i?l=o:c=o;n(l\*t+a\*(1-t))}s.\_\_wrap\_o||"undefined"!=typeof ResizeObserver&&(s.\_\_wrap\_o=new ResizeObserver(()=>{self.\_\_wrap\_b(0,+s.dataset.brr,s)})).observe(r)};self.\_\_wrap\_n!=1&&self.\_\_wrap\_b(":R2nb6unhn6uf:",1) [Learn About Managed Next.js](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=showcase_redesign&utm_campaign=footer_learn_cta)[Contact Sales](https://vercel.com/contact/sales/nextjs?utm_source=next_site&utm_medium=showcase_redesign&utm_campaign=footer_learn_cta)
{ "contentLength": null, "etag": "W/\"149fcee0bef4b6599f3f5d4e592cb920\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/data-fetching/patterns
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [ Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Fetching data on the server](#fetching-data-on-the-server) * [Fetching data where it's needed](#fetching-data-where-its-needed) * [Streaming](#streaming) * [Parallel and sequential data fetching](#parallel-and-sequential-data-fetching) * [Sequential Data Fetching](#sequential-data-fetching) * [Parallel Data Fetching](#parallel-data-fetching) * [Preloading Data](#preloading-data) * [Using React cache, server-only, and the Preload Pattern](#using-react-cache-server-only-and-the-preload-pattern) * [Preventing sensitive data from being exposed to the client](#preventing-sensitive-data-from-being-exposed-to-the-client) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/02-data-fetching/03-patterns.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Data Fetching](/docs/app/building-your-application/data-fetching)Data Fetching Patterns and Best Practices Patterns and Best Practices =========================== There are a few recommended patterns and best practices for fetching data in React and Next.js. This page will go over some of the most common patterns and how to use them. [Fetching data on the server](#fetching-data-on-the-server) ----------------------------------------------------------- Whenever possible, we recommend fetching data on the server with Server Components. This allows you to: * Have direct access to backend data resources (e.g. databases). * Keep your application more secure by preventing sensitive information, such as access tokens and API keys, from being exposed to the client. * Fetch data and render in the same environment. This reduces both the back-and-forth communication between client and server, as well as the [work on the main thread](https://vercel.com/blog/how-react-18-improves-application-performance) on the client. * Perform multiple data fetches with single round-trip instead of multiple individual requests on the client. * Reduce client-server [waterfalls](#parallel-and-sequential-data-fetching). * Depending on your region, data fetching can also happen closer to your data source, reducing latency and improving performance. Then, you can mutate or update data with [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). [Fetching data where it's needed](#fetching-data-where-its-needed) ------------------------------------------------------------------ If you need to use the same data (e.g. current user) in multiple components in a tree, you do not have to fetch data globally, nor forward props between components. Instead, you can use `fetch` or React `cache` in the component that needs the data without worrying about the performance implications of making multiple requests for the same data. This is possible because `fetch` requests are automatically memoized. Learn more about [request memoization](/docs/app/building-your-application/caching#request-memoization) > **Good to know**: This also applies to layouts, since it's not possible to pass data between a parent layout and its children. [Streaming](#streaming) ----------------------- Streaming and [Suspense](https://react.dev/reference/react/Suspense) are React features that allow you to progressively render and incrementally stream rendered units of the UI to the client. With Server Components and [nested layouts](/docs/app/building-your-application/routing/pages-and-layouts), you're able to instantly render parts of the page that do not specifically require data, and show a [loading state](/docs/app/building-your-application/routing/loading-ui-and-streaming) for parts of the page that are fetching data. This means the user does not have to wait for the entire page to load before they can start interacting with it. ![Server Rendering with Streaming](/_next/image?url=%2Fdocs%2Flight%2Fserver-rendering-with-streaming.png&w=3840&q=75)![Server Rendering with Streaming](/_next/image?url=%2Fdocs%2Fdark%2Fserver-rendering-with-streaming.png&w=3840&q=75) To learn more about Streaming and Suspense, see the [Loading UI](/docs/app/building-your-application/routing/loading-ui-and-streaming) and [Streaming and Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense) pages. [Parallel and sequential data fetching](#parallel-and-sequential-data-fetching) ------------------------------------------------------------------------------- When fetching data inside React components, you need to be aware of two data fetching patterns: Parallel and Sequential. ![Sequential and Parallel Data Fetching](/_next/image?url=%2Fdocs%2Flight%2Fsequential-parallel-data-fetching.png&w=3840&q=75)![Sequential and Parallel Data Fetching](/_next/image?url=%2Fdocs%2Fdark%2Fsequential-parallel-data-fetching.png&w=3840&q=75) * With **sequential data fetching**, requests in a route are dependent on each other and therefore create waterfalls. There may be cases where you want this pattern because one fetch depends on the result of the other, or you want a condition to be satisfied before the next fetch to save resources. However, this behavior can also be unintentional and lead to longer loading times. * With **parallel data fetching**, requests in a route are eagerly initiated and will load data at the same time. This reduces client-server waterfalls and the total time it takes to load data. ### [Sequential Data Fetching](#sequential-data-fetching) If you have nested components, and each component fetches its own data, then data fetching will happen sequentially if those data requests are different (this doesn't apply to requests for the same data as they are automatically [memoized](/docs/app/building-your-application/caching#request-memoization)). For example, the `Playlists` component will only start fetching data once the `Artist` component has finished fetching data because `Playlists` depends on the `artistID` prop: app/artist/\[username\]/page.tsx TypeScript JavaScriptTypeScript // ... async function Playlists({ artistID }: { artistID: string }) { // Wait for the playlists const playlists = await getArtistPlaylists(artistID) return ( <ul> {playlists.map((playlist) => ( <li key={playlist.id}>{playlist.name}</li> ))} </ul> ) } export default async function Page({ params: { username }, }: { params: { username: string } }) { // Wait for the artist const artist = await getArtist(username) return ( <> <h1>{artist.name}</h1> <Suspense fallback={<div>Loading...</div>}> <Playlists artistID={artist.id} /> </Suspense> </> ) } In cases like this, you can use [`loading.js`](/docs/app/building-your-application/routing/loading-ui-and-streaming) (for route segments) or [React `<Suspense>`](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense) (for nested components) to show an instant loading state while React streams in the result. This will prevent the whole route from being blocked by data fetching, and the user will be able to interact with the parts of the page that are not blocked. > **Blocking Data Requests:** > > An alternative approach to prevent waterfalls is to fetch data globally, at the root of your application, but this will block rendering for all route segments beneath it until the data has finished loading. This can be described as "all or nothing" data fetching. Either you have the entire data for your page or application, or none. > > Any fetch requests with `await` will block rendering and data fetching for the entire tree beneath it, unless they are wrapped in a `<Suspense>` boundary or `loading.js` is used. Another alternative is to use [parallel data fetching](#parallel-data-fetching) or the [preload pattern](#preloading-data). ### [Parallel Data Fetching](#parallel-data-fetching) To fetch data in parallel, you can eagerly initiate requests by defining them outside the components that use the data, then calling them from inside the component. This saves time by initiating both requests in parallel, however, the user won't see the rendered result until both promises are resolved. In the example below, the `getArtist` and `getArtistAlbums` functions are defined outside the `Page` component, then called inside the component, and we wait for both promises to resolve: app/artist/\[username\]/page.tsx TypeScript JavaScriptTypeScript import Albums from './albums' async function getArtist(username: string) { const res = await fetch(`https://api.example.com/artist/${username}`) return res.json() } async function getArtistAlbums(username: string) { const res = await fetch(`https://api.example.com/artist/${username}/albums`) return res.json() } export default async function Page({ params: { username }, }: { params: { username: string } }) { // Initiate both requests in parallel const artistData = getArtist(username) const albumsData = getArtistAlbums(username) // Wait for the promises to resolve const [artist, albums] = await Promise.all([artistData, albumsData]) return ( <> <h1>{artist.name}</h1> <Albums list={albums}></Albums> </> ) } To improve the user experience, you can add a [Suspense Boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming) to break up the rendering work and show part of the result as soon as possible. [Preloading Data](#preloading-data) ----------------------------------- Another way to prevent waterfalls is to use the preload pattern. You can optionally create a `preload` function to further optimize parallel data fetching. With this approach, you don't have to pass promises down as props. The `preload` function can also have any name as it's a pattern, not an API. components/Item.tsx TypeScript JavaScriptTypeScript import { getItem } from '@/utils/get-item' export const preload = (id: string) => { // void evaluates the given expression and returns undefined // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/void void getItem(id) } export default async function Item({ id }: { id: string }) { const result = await getItem(id) // ... } app/item/\[id\]/page.tsx TypeScript JavaScriptTypeScript import Item, { preload, checkIsAvailable } from '@/components/Item' export default async function Page({ params: { id }, }: { params: { id: string } }) { // starting loading item data preload(id) // perform another asynchronous task const isAvailable = await checkIsAvailable() return isAvailable ? <Item id={id} /> : null } ### [Using React `cache`, `server-only`, and the Preload Pattern](#using-react-cache-server-only-and-the-preload-pattern) You can combine the `cache` function, the `preload` pattern, and the `server-only` package to create a data fetching utility that can be used throughout your app. utils/get-item.ts TypeScript JavaScriptTypeScript import { cache } from 'react' import 'server-only' export const preload = (id: string) => { void getItem(id) } export const getItem = cache(async (id: string) => { // ... }) With this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching [only happens on the server](/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment). The `utils/get-item` exports can be used by Layouts, Pages, or other components to give them control over when an item's data is fetched. > **Good to know:** > > * We recommend using the [`server-only` package](/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment) to make sure server data fetching functions are never used on the client. [Preventing sensitive data from being exposed to the client](#preventing-sensitive-data-from-being-exposed-to-the-client) ------------------------------------------------------------------------------------------------------------------------- We recommend using React's taint APIs, [`taintObjectReference`](https://react.dev/reference/react/experimental_taintObjectReference) and [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue), to prevent whole object instances or sensitive values from being passed to the client. To enable tainting in your application, set the Next.js Config `experimental.taint` option to `true`: next.config.js module.exports = { experimental: { taint: true, }, } Then pass the object or value you want to taint to the `experimental_taintObjectReference` or `experimental_taintUniqueValue` functions: app/utils.ts TypeScript JavaScriptTypeScript import { queryDataFromDB } from './api' import { experimental_taintObjectReference, experimental_taintUniqueValue, } from 'react' export async function getUserData() { const data = await queryDataFromDB() experimental_taintObjectReference( 'Do not pass the whole user object to the client', data ) experimental_taintUniqueValue( "Do not pass the user's address to the client", data, data.address ) return data } app/page.tsx TypeScript JavaScriptTypeScript import { getUserData } from './data' export async function Page() { const userData = getUserData() return ( <ClientComponent user={userData} // this will cause an error because of taintObjectReference address={userData.address} // this will cause an error because of taintUniqueValue /> ) } Learn more about [Security and Server Actions](https://nextjs.org/blog/security-nextjs-server-components-actions). [Previous Server Actions and Mutations ](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) [Next Rendering ](/docs/app/building-your-application/rendering) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"c6e0e33eac4004cd083bec51a0c632d1\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/learn?utm_source=next-site&utm_medium=navbar
Start building with Next.js =========================== Go from beginner to expert by learning the foundations of Next.js and building a fully functional demo website that uses all the latest features. Learn Next.js Learn Next.js 16 chapters that take you from React to Next.js. [Placeholder](/learn) Learn React Foundations New to React? Learn how to go from JavaScript to React with this Foundations course. [React Foundations](/learn/react-foundations) How does the course work? ------------------------- By building a full web application. Step by step. ![Course explainer](/_next/image?url=%2Flearn%2Fcourse-explainer.png&w=1920&q=75)![Course explainer](/_next/image?url=%2Flearn%2Fcourse-explainer-small.png&w=1920&q=75) Set up your local environment and initializing the "ACME" Next.js project template. Use pre-styled components as part of each chapter that leverage Next.js conventions and patterns. Hook up real application logic and data to bring a fully-fledged demo website to life. At the end you’ll have a website that’s ready to ship and the knowledge to build and deploy your own. Your progress will be synced as you complete chapters Go at your own pace and pick up where you left off Test your knowledge during each chapter Take quick quizzes to see what you’ve learned What will I learn? ------------------ Here’s everything that’s covered in the course. [ Introduction Learn how to build a full-stack web application with the free, Next.js App Router Course. ](/learn/dashboard-app) [ 1 Getting Started Create a new Next.js application using the dashboard starter example and explore the project. ](/learn/dashboard-app/getting-started) [ 2 CSS Styling Style your Next.js application with Tailwind and CSS modules. ](/learn/dashboard-app/css-styling) [ 3 Optimizing Fonts and Images Optimize fonts and images with the Next.js built-in components. ](/learn/dashboard-app/optimizing-fonts-images) [ 4 Creating Layouts and Pages Create the dashboard routes and a shared layout that can be shared between multiple pages. ](/learn/dashboard-app/creating-layouts-and-pages) [ 5 Navigating Between Pages Learn how to use the <Link> component to navigate between pages. ](/learn/dashboard-app/navigating-between-pages) [ 6 Setting Up Your Database Setup a database for your application and seed it with initial data. ](/learn/dashboard-app/setting-up-your-database) [ 7 Fetching Data Learn about the different ways to fetch data in Next.js, and fetch data for your dashboard page using Server Components. ](/learn/dashboard-app/fetching-data) [ 8 Static and Dynamic Rendering Understand how rendering works in Next.js, and make your dashboard app dynamic. ](/learn/dashboard-app/static-and-dynamic-rendering) [ 9 Streaming Improve your application's loading experience with streaming and loading skeletons. ](/learn/dashboard-app/streaming) [ 10 Partial Prerendering An early look into Partial Prerendering and how it works. ](/learn/dashboard-app/partial-prerendering) [ 11 Adding Search and Pagination Add search and pagination to your dashboard application using Next.js APIs. ](/learn/dashboard-app/adding-search-and-pagination) [ 12 Mutating Data Mutate data using React Server Actions, and revalidate the Next.js cache. ](/learn/dashboard-app/mutating-data) [ 13 Handling Errors Handle errors gracefully with error.tsx and notFound. ](/learn/dashboard-app/error-handling) [ 14 Improving Accessibility Implement server-side form validation and improve accessibility in your forms. ](/learn/dashboard-app/improving-accessibility) [ 15 Adding Authentication Add authentication to protect your dashboard routes using NextAuth.js, Server Actions, and Middleware. ](/learn/dashboard-app/adding-authentication) [ 16 Adding Metadata Learn how to add metadata to your Next.js application. ](/learn/dashboard-app/adding-metadata) [ 17 Next Steps Next.js Dashboard Course Conclusion ](/learn/dashboard-app/next-steps) [Placeholder](/learn) Looking to go deeper? Continue learning by using our guides. [View All Guides](https://vercel.com/guides?topics=frameworks) [ How to build a fullstack app with Next.js, Prisma and Postgres Build, Deployment & Git ](https://vercel.com/guides/nextjs-prisma-postgres)[ Build a multi-tenant app with custom domains using Next.js Build, Deployment & Git ](https://vercel.com/guides/nextjs-multi-tenant-application)[ Integrating Next.js and Contentful for your headless CMS Databases & CMS ](https://vercel.com/guides/integrating-next-js-and-contentful-for-your-headless-cms)[ Building Ecommerce Sites with Next.js and Shopify Databases & CMS ](https://vercel.com/guides/building-ecommerce-sites-with-next-js-and-shopify)[ Using headless WordPress with Next.js and Vercel Databases & CMS ](https://vercel.com/guides/wordpress-with-vercel) Next.js Documentation The complete resource for installing, running, building with, and deploying Next.js [View the Documentation](https://nextjs.org/docs)
{ "contentLength": null, "etag": "W/\"d71d84974714e6b5b027cab81889329e\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [ sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Sitemap files (.xml)](#sitemap-files-xml) * [Generating a sitemap using code (.js, .ts)](#generating-a-sitemap-using-code-js-ts) * [Generate a localized Sitemap](#generate-a-localized-sitemap) * [Generating multiple sitemaps](#generating-multiple-sitemaps) * [Returns](#returns) * [Version History](#version-history) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/01-metadata/sitemap.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference/file-conventions)[Metadata Files](/docs/app/api-reference/file-conventions/metadata)sitemap.xml sitemap.xml =========== `sitemap.(xml|js|ts)` is a special file that matches the [Sitemaps XML format](https://www.sitemaps.org/protocol.html) to help search engine crawlers index your site more efficiently. ### [Sitemap files (.xml)](#sitemap-files-xml) For smaller applications, you can create a `sitemap.xml` file and place it in the root of your `app` directory. app/sitemap.xml <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://acme.com</loc> <lastmod>2023-04-06T15:02:24.021Z</lastmod> <changefreq>yearly</changefreq> <priority>1</priority> </url> <url> <loc>https://acme.com/about</loc> <lastmod>2023-04-06T15:02:24.021Z</lastmod> <changefreq>monthly</changefreq> <priority>0.8</priority> </url> <url> <loc>https://acme.com/blog</loc> <lastmod>2023-04-06T15:02:24.021Z</lastmod> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> </urlset> ### [Generating a sitemap using code (.js, .ts)](#generating-a-sitemap-using-code-js-ts) You can use the `sitemap.(js|ts)` file convention to programmatically **generate** a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a [`Sitemap`](#returns) type is available. app/sitemap.ts TypeScript JavaScriptTypeScript import { MetadataRoute } from 'next' export default function sitemap(): MetadataRoute.Sitemap { return [ { url: 'https://acme.com', lastModified: new Date(), changeFrequency: 'yearly', priority: 1, }, { url: 'https://acme.com/about', lastModified: new Date(), changeFrequency: 'monthly', priority: 0.8, }, { url: 'https://acme.com/blog', lastModified: new Date(), changeFrequency: 'weekly', priority: 0.5, }, ] } Output: acme.com/sitemap.xml <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://acme.com</loc> <lastmod>2023-04-06T15:02:24.021Z</lastmod> <changefreq>yearly</changefreq> <priority>1</priority> </url> <url> <loc>https://acme.com/about</loc> <lastmod>2023-04-06T15:02:24.021Z</lastmod> <changefreq>monthly</changefreq> <priority>0.8</priority> </url> <url> <loc>https://acme.com/blog</loc> <lastmod>2023-04-06T15:02:24.021Z</lastmod> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> </urlset> ### [Generate a localized Sitemap](#generate-a-localized-sitemap) app/sitemap.ts TypeScript JavaScriptTypeScript import { MetadataRoute } from 'next' export default function sitemap(): MetadataRoute.Sitemap { return [ { url: 'https://acme.com', lastModified: new Date(), alternates: { languages: { es: 'https://acme.com/es', de: 'https://acme.com/de', }, }, }, { url: 'https://acme.com/about', lastModified: new Date(), alternates: { languages: { es: 'https://acme.com/es/about', de: 'https://acme.com/de/about', }, }, }, { url: 'https://acme.com/blog', lastModified: new Date(), alternates: { languages: { es: 'https://acme.com/es/blog', de: 'https://acme.com/de/blog', }, }, }, ] } Output: acme.com/sitemap.xml <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://acme.com</loc> <xhtml:link rel="alternate" hreflang="es" href="https://acme.com/es"/> <xhtml:link rel="alternate" hreflang="de" href="https://acme.com/de"/> <lastmod>2023-04-06T15:02:24.021Z</lastmod> </url> <url> <loc>https://acme.com/about</loc> <xhtml:link rel="alternate" hreflang="es" href="https://acme.com/es/about"/> <xhtml:link rel="alternate" hreflang="de" href="https://acme.com/de/about"/> <lastmod>2023-04-06T15:02:24.021Z</lastmod> </url> <url> <loc>https://acme.com/blog</loc> <xhtml:link rel="alternate" hreflang="es" href="https://acme.com/es/blog"/> <xhtml:link rel="alternate" hreflang="de" href="https://acme.com/de/blog"/> <lastmod>2023-04-06T15:02:24.021Z</lastmod> </url> </urlset> ### [Generating multiple sitemaps](#generating-multiple-sitemaps) While a single sitemap will work for most applications. For large web applications, you may need to split a sitemap into multiple files. There are two ways you can create multiple sitemaps: * By nesting `sitemap.(xml|js|ts)` inside multiple route segments e.g. `app/sitemap.xml` and `app/products/sitemap.xml`. * By using the [`generateSitemaps`](/docs/app/api-reference/functions/generate-sitemaps) function. For example, to split a sitemap using `generateSitemaps`, return an array of objects with the sitemap `id`. Then, use the `id` to generate the unique sitemaps. app/product/sitemap.ts TypeScript JavaScriptTypeScript import { BASE_URL } from '@/app/lib/constants' export async function generateSitemaps() { // Fetch the total number of products and calculate the number of sitemaps needed return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }] } export default async function sitemap({ id, }: { id: number }): Promise<MetadataRoute.Sitemap> { // Google's limit is 50,000 URLs per sitemap const start = id * 50000 const end = start + 50000 const products = await getProducts( `SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}` ) return products.map((product) => ({ url: `${BASE_URL}/product/${id}`, lastModified: product.date, })) } In production, your generated sitemaps will be available at `/.../sitemap/[id].xml`. For example, `/product/sitemap/1.xml`. In development, you can view the generated sitemap on `/.../sitemap.xml/[id]`. For example, `/product/sitemap.xml/1`. This difference is temporary and will follow the production format. See the [`generateSitemaps` API reference](/docs/app/api-reference/functions/generate-sitemaps) for more information. [Returns](#returns) ------------------- The default function exported from `sitemap.(xml|ts|js)` should return an array of objects with the following properties: type Sitemap = Array<{ url: string lastModified?: string | Date changeFrequency?: | 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never' priority?: number alternates?: { languages?: Languages<string> } }> [Version History](#version-history) ----------------------------------- Version Changes `v13.4.5` Add `changeFrequency` and `priority` attributes to sitemaps. `v13.3.0` `sitemap` introduced. Next Steps ---------- Learn how to use the generateSitemaps function. [ App Router ... Functions ### generateSitemaps Learn how to use the generateSiteMaps function to create multiple sitemaps for your application. ](/docs/app/api-reference/functions/generate-sitemaps) [Previous robots.txt ](/docs/app/api-reference/file-conventions/metadata/robots) [Next Functions ](/docs/app/api-reference/functions) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"f0d8b555bc7403466b72bf0e5f18e66c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/blog
The latest Next.js news ======================= May 23rd, 2024 ![](/_next/image?url=%2Fstatic%2Fteam%2Fdelba.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fzack.jpg&w=48&q=75) [Next.js 15 RC](/blog/next-15-rc) The Next.js 15 Release Candidate (RC) is now available. This early version allows you to test the latest features before the upcoming stable release. * [React RC](/blog/next-15-rc#react-19-rc) * [Caching defaults changes](/blog/next-15-rc#caching-updates) * [Incremental Partial Prerendering adoption](/blog/next-15-rc#incremental-adoption-of-partial-prerendering-experimental) * [next/after (Experimental)](/blog/next-15-rc#executing-code-after-a-response-with-nextafter-experimental) * [New create-next-app design](/blog/next-15-rc#create-next-app-updates) * [Bundling external packages (Stable)](/blog/next-15-rc#optimizing-bundling-of-external-packages-stable) [Read More](/blog/next-15-rc) April 11th, 2024 ![](/_next/image?url=%2Fstatic%2Fteam%2Fdelba.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 14.2](/blog/next-14-2) Next.js 14.2 includes development, production, and caching improvements. * [Turbopack (Release Candidate)](/blog/next-14-2#turbopack-for-development-release-candidate) * [Caching Improvements](/blog/next-14-2#caching-improvements) * [Build and Production Improvements](/blog/next-14-2#build-and-production-improvements) * [Errors DX Improvements](/blog/next-14-2#errors-dx-improvements) [Read More](/blog/next-14-2) January 18th, 2024 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjiachi.png&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjimmy.jpg&w=48&q=75) [Next.js 14.1](/blog/next-14-1) Next.js 14.1 includes developer experience improvements including: * [Improved Self-Hosting](/blog/next-14-1#improved-self-hosting) * [Turbopack Improvements](/blog/next-14-1#turbopack-improvements) * [DX Improvements](/blog/next-14-1#developer-experience-improvements) * [Parallel & Intercepted Routes](/blog/next-14-1#parallel--intercepted-routes) * [`next/image` Improvements](/blog/next-14-1#nextimage-support-for-picture-and-art-direction) [Read More](/blog/next-14-1) October 26th, 2023 ![](/_next/image?url=%2Fstatic%2Fteam%2Flee.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 14](/blog/next-14) As we announced at [Next.js Conf](https://nextjs.org/conf), Next.js 14 is our most focused release with: * [Turbopack](/blog/next-14#nextjs-compiler-turbocharged) * **53% faster** local server startup * **94% faster** code updates * [Server Actions (Stable)](/blog/next-14#forms-and-mutations) * [Partial Prerendering (Preview)](/blog/next-14#partial-prerendering-preview) * [Next.js Learn (New)](/blog/next-14#nextjs-learn-course) [Read More](/blog/next-14) October 23rd, 2023 ![](/_next/image?url=%2Fstatic%2Fteam%2Fseb.jpg&w=48&q=75) [How to Think About Security in Next.js](/blog/security-nextjs-server-components-actions) React Server Components (RSC) in App Router is a novel paradigm that eliminates much of the redundancy and potential risks linked with conventional methods. Given the newness, developers and subsequently security teams may find it challenging to align their existing security protocols with this model. [Read More](/blog/security-nextjs-server-components-actions) September 19th, 2023 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjimmy.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fsokra.jpg&w=48&q=75) [Next.js 13.5](/blog/next-13-5) Next.js 13.5 improves local dev performance and reliability with: * [22% faster local server startup](/blog/next-13-5#improving-startup-and-fast-refresh-time) * [29% faster HMR (Fast Refresh)](/blog/next-13-5#improving-startup-and-fast-refresh-time) * [40% less memory usage](/blog/next-13-5#improving-startup-and-fast-refresh-time) * [Optimized Package Imports](/blog/next-13-5#optimized-package-imports) * [`next/image` Improvements](/blog/next-13-5#nextimage-improvements) * [And over 438 bugs patched!](/blog/next-13-5#other-improvements) [Read More](/blog/next-13-5) June 22nd, 2023 ![](/_next/image?url=%2Fstatic%2Fteam%2Fdelba.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Flee.jpg&w=48&q=75) [Next.js App Router Update](/blog/june-2023-update) For the next release (and coming months) we're focused on the following areas: * **Performance** * **Stability** * **Developer Experience** [Read More](/blog/june-2023-update) May 4th, 2023 ![](/_next/image?url=%2Fstatic%2Fteam%2Fseb.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 13.4](/blog/next-13-4) Next.js 13.4 is a foundational release, marking stability for the App Router: * [App Router (Stable)](/blog/next-13-4#nextjs-app-router) * [Turbopack (Beta)](/blog/next-13-4#turbopack-beta) * [Server Actions (Alpha)](/blog/next-13-4#server-actions-alpha) [Read More](/blog/next-13-4) April 6th, 2023 ![](/_next/image?url=%2Fstatic%2Fteam%2Fdelba.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 13.3](/blog/next-13-3) Next.js 13.3 adds popular community-requested features and is the last release before the App Router is stable, including: * [File-Based Metadata API](/blog/next-13-3#file-based-metadata-api) * [Dynamic Open Graph Images](/blog/next-13-3#dynamic-open-graph-image-generation) * [Static Export for App Router](/blog/next-13-3#static-export-for-app-router) * [Parallel Routes and Interception](/blog/next-13-3#parallel-routes-and-interception) [Read More](/blog/next-13-3) February 23rd, 2023 ![](/_next/image?url=%2Fstatic%2Fteam%2Fcasey.png&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjimmy.jpg&w=48&q=75) +1![](/_next/image?url=%2Fstatic%2Fteam%2Fluba.png&w=48&q=75) [Next.js 13.2](/blog/next-13-2) Next.js 13.2 includes major improvements to the App Router (`app`) in preparation for stability: * [Built-in SEO Support](/blog/next-13-2#built-in-seo-support-with-new-metadata-api) * [Route Handlers](/blog/next-13-2#custom-route-handlers) * [MDX for Server Components](/blog/next-13-2#mdx-for-server-components) * [Rust MDX Parser](/blog/next-13-2#rust-mdx-parser) * [Improved Error Overlay](/blog/next-13-2#improved-error-overlay) * [Statically Typed Links (Beta)](/blog/next-13-2#statically-typed-links) * [Turbopack Improvements (Alpha)](/blog/next-13-2#turbopack-improvements) * [Next.js Cache (Beta)](/blog/next-13-2#nextjs-cache) [Read More](/blog/next-13-2) December 22nd, 2022 ![](/_next/image?url=%2Fstatic%2Fteam%2Foj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 13.1](/blog/next-13-1) Next.js 13.1 includes improvements to both the `pages` and `app` directories: * [`app` Directory (Beta) Improvements](/blog/next-13-1#improved-stability-and-support-for-app-directory) * [Built-in Module Transpilation](/blog/next-13-1#built-in-module-transpilation-stable) * [Edge Runtime (Stable)](#a-light-nodejs-runtime-for-the-edge-now-stable-for-api-routes) * [Turbopack Updates](/blog/next-13-1#turbopack-improvements) * [Middleware Improvements](/blog/next-13-1#nextjs-advanced-middleware) * [SWC Import Resolution](/blog/next-13-1#import-resolution-for-smaller-bundles) [Read More](/blog/next-13-1) October 25th, 2022 ![](/_next/image?url=%2Fstatic%2Fteam%2Fbalazs.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fdelba.jpg&w=48&q=75) +8![](/_next/image?url=%2Fstatic%2Fteam%2Fkdy.jpg&w=48&q=75) [Next.js 13](/blog/next-13) As we announced at [Next.js Conf](https://nextjs.org/conf), Next.js 13 (stable) lays the foundations to be dynamic without limits: * [`app/` Directory (beta)](/blog/next-13#new-app-directory-beta) * [Layouts](/blog/next-13#layouts) * [React Server Components](/blog/next-13#server-components) * [Streaming](/blog/next-13#streaming) * [Turbopack (alpha)](/blog/next-13#introducing-turbopack-alpha) * [New `next/image` (stable)](/blog/next-13#nextimage) * [New `@next/font` (beta)](/blog/next-13#nextfont) * [Improved `next/link`](/blog/next-13#breaking-changes) [Read More](/blog/next-13) September 8th, 2022 ![](/_next/image?url=%2Fstatic%2Fteam%2Fbalazs.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fkdy.jpg&w=48&q=75) +5![](/_next/image?url=%2Fstatic%2Fteam%2Fjiachi.png&w=48&q=75) [Next.js 12.3](/blog/next-12-3) We've shipped some quality-of-life improvements to Next.js with 12.3: * [Improved Fast Refresh](/blog/next-12-3#improved-fast-refresh) * [TypeScript Auto-Install](/blog/next-12-3#typescript-auto-install) * [Image Component](/blog/next-12-3#image-component) * [SWC Minifier](/blog/next-12-3##swc-minifier-stable) * [New Router + Layouts Update](/blog/next-12-3#new-router-and-layouts-update) [Read More](/blog/next-12-3) June 28th, 2022 ![](/_next/image?url=%2Fstatic%2Fteam%2Fbalazs.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fkdy.jpg&w=48&q=75) +8![](/_next/image?url=%2Fstatic%2Fteam%2Fjavi.jpg&w=48&q=75) [Next.js 12.2](/blog/next-12-2) We're laying the foundation for the future of Next.js with 12.2: * [Middleware (Stable)](/blog/next-12-2#middleware-stable) * [On-Demand ISR (Stable)](/blog/next-12-2#on-demand-incremental-static-regeneration-stable) * [Edge API Routes (Experimental)](/blog/next-12-2#edge-api-routes-experimental) * [Edge SSR (Experimental)](/blog/next-12-2#edge-server-rendering-experimental) * [SWC Plugins (Experimental)](/blog/next-12-2#swc-plugins-experimental) * [Improvements to `next/image`](/blog/next-12-2#improvements-to-nextimage) [Read More](/blog/next-12-2) May 23rd, 2022 ![](/_next/image?url=%2Fstatic%2Fteam%2Fdelba.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Flee.jpg&w=48&q=75) +1![](/_next/image?url=%2Fstatic%2Fteam%2Fseb.jpg&w=48&q=75) [Layouts RFC](/blog/layouts-rfc) This RFC outlines the biggest update to Next.js since it was introduced in 2016: * **Nested Layouts:** Build complex applications with nested routes. * **Designed for Server Components:** Optimized for subtree navigation. * **Improved Data Fetching:** Fetch in layouts while avoiding waterfalls. * **Using React 18 Features:** Streaming, Transitions, and Suspense. * **Client and Server Routing:** Server-centric routing with _SPA-like_ behavior. * **100% incrementally adoptable**: No breaking changes so you can adopt gradually. * **Advanced Routing Conventions**: Offscreen stashing, instant transitions, and more. [Read More](/blog/layouts-rfc) February 17th, 2022 ![](/_next/image?url=%2Fstatic%2Fteam%2Fbalazs.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fkdy.jpg&w=48&q=75) +9![](/_next/image?url=%2Fstatic%2Fteam%2Fgerald.jpg&w=48&q=75) [Next.js 12.1](/blog/next-12-1) We're excited to release one of our most requested features with Next.js 12.1: * [On-demand ISR (Beta)](/blog/next-12-1#on-demand-incremental-static-regeneration-beta) * [Expanded Support for SWC](/blog/next-12-1#improved-swc-support) * [`next/jest` Plugin](/blog/next-12-1#zero-configuration-jest-plugin) * [Faster Minification with SWC (RC)](/blog/next-12-1#faster-minification-with-swc) * [Self-Hosting Improvements](/blog/next-12-1#self-hosted-nextjs-improvements) * [React 18 & Server Components (Alpha)](/blog/next-12-1#react-18-server-components-and-ssr-streaming-alpha) * [Developer Survey](/blog/next-12-1#nextjs-developer-survey) [Read More](/blog/next-12-1) October 26th, 2021 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fkdy.jpg&w=48&q=75) +9![](/_next/image?url=%2Fstatic%2Fteam%2Fgerald.jpg&w=48&q=75) [Next.js 12](/blog/next-12) As we announced at [Next.js Conf](https://nextjs.org/conf), Next.js 12 is our biggest release ever: * [Rust Compiler](/blog/next-12#faster-builds-and-fast-refresh-with-rust-compiler) * [Middleware (beta)](/blog/next-12#introducing-middleware) * [React 18 Support](/blog/next-12#preparing-for-react-18) * [`<Image />` AVIF Support](/blog/next-12#smaller-images-using-avif) * [Bot-aware ISR Fallback](/blog/next-12#bot-aware-isr-fallback) * [Native ES Modules Support](/blog/next-12#es-modules-support-and-url-imports) * [URL Imports (alpha)](/blog/next-12#url-imports) * [React Server Components (alpha)](/blog/next-12#react-server-components) [Read More](/blog/next-12) August 11th, 2021 ![](/_next/image?url=%2Fstatic%2Fteam%2Fkdy.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjiachi.png&w=48&q=75) +5![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) [Next.js 11.1](/blog/next-11-1) We're improving build performance across the entire stack with Next.js 11.1, featuring: * [Security Patch](/blog/next-11-1#security-patch) * [ES Modules Support](/blog/next-11-1#es-modules-support) * [Rust-based Tooling](/blog/next-11-1#adopting-rust-based-swc) * [Faster Data Fetching](/blog/next-11-1#builds--data-fetching) * [Faster Source Maps](/blog/next-11-1#source-maps) * [ESLint Integration Improvements](/blog/next-11-1#eslint-improvements) * [`next/image` Improvements](/blog/next-11-1#nextimage-improvements) [Read More](/blog/next-11-1) June 15th, 2021 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fshu.jpg&w=48&q=75) +1![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 11](/blog/next-11) Our mission to create the best developer experience continues with Next.js 11, featuring: * [Conformance](/blog/next-11#conformance) * [Improved Performance](/blog/next-11#improved-performance) * [`next/script`](/blog/next-11#script-optimization) * [`next/image` Improvements](/blog/next-11#image-improvements) * [Webpack 5](/blog/next-11#webpack-5) * [Create React App Migration (Experimental)](/blog/next-11#cra-migration) * [Next.js Live (Preview Release)](/blog/next-11#nextjs-live-preview-release) [Read More](/blog/next-11) April 28th, 2021 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) +2![](/_next/image?url=%2Fstatic%2Fteam%2Fshu.jpg&w=48&q=75) [Next.js 10.2](/blog/next-10-2) We are excited to introduce Next.js 10.2, featuring: * [Faster Builds](/blog/next-10-2#webpack-5) * [Faster Refresh](/blog/next-10-2#webpack-5) * [Faster Startup](/blog/next-10-2#improved-startup-performance) * [Improved Accessibility](/blog/next-10-2#accessibility-improvements) * [More Flexible Redirects and Rewrites](/blog/next-10-2#routing-based-on-headers-and-query-string-parameters) * [Automatic Webfont Optimization](/blog/next-10-2#automatic-webfont-optimization) [Read More](/blog/next-10-2) March 29th, 2021 ![](/_next/image?url=%2Fstatic%2Fteam%2Fbel.png&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) +5![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) [Next.js 10.1](/blog/next-10-1) We are excited to introduce Next.js 10.1, featuring: * [3x Faster Refresh](/blog/next-10-1#3x-faster-refresh) * [Improved Installation Time](/blog/next-10-1#improved-installation-time) * [`next/image` Improvements](/blog/next-10-1#nextimage-improvements) * [Next.js Commerce Shopify Integration](/blog/next-10-1#nextjs-commerce-shopify-integration) * [Custom 500 Page](/blog/next-10-1#custom-500-page) * [Strict PostCSS Configuration Loading](/blog/next-10-1#strict-postcss-configuration-loading) * [Support for `extends` in `tsconfig.json`](/blog/next-10-1#support-for-extends-in-tsconfigjson) * [Detect When Preview Mode Is Enabled](/blog/next-10-1#detect-when-preview-mode-is-enabled) * [Router Methods Scroll to Top](/blog/next-10-1#router-methods-scroll-to-top) * [Documentation Improvements](/blog/next-10-1#documentation-improvements) [Read More](/blog/next-10-1) November 18th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Flee.jpg&w=48&q=75) [Incrementally Adopting Next.js](/blog/incremental-adoption) [Next.js](https://nextjs.org/) has been designed for gradual adoption. With Next.js, you can continue using your existing code and add as much (or as little) React as you need. By starting small and incrementally adding more pages, you can prevent derailing feature work by avoiding a complete rewrite. Many companies need to modernize their tech stack to reduce costs, increase developer productivity, and provide the best experience for their customers. Component-driven development has greatly improved the deployment velocity and reusability of modern codebases. And with over [8 million downloads/month](https://www.npmtrends.com/react), React is the leading component-driven choice for developers. Next.js, the React framework for production, enables you to incrementally adopt React. [Read More](/blog/incremental-adoption) October 27th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Fbel.png&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) +5![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) [Next.js 10](/blog/next-10) We are excited to introduce Next.js 10, featuring: * [Built-in Image Component and Automatic Image Optimization](/blog/next-10#built-in-image-component-and-automatic-image-optimization) * [Internationalized Routing](/blog/next-10#internationalized-routing) * [Next.js Analytics](/blog/next-10#nextjs-analytics) * [Next.js Commerce](/blog/next-10#nextjs-commerce) * [React 17 Support](/blog/next-10#react-17-support) * [getStaticProps / getServerSideProps Fast Refresh](/blog/next-10#getstaticprops--getserversideprops-fast-refresh) * [Fast Refresh for MDX](/blog/next-10#fast-refresh-for-mdx) * [Importing CSS from Third Party React Components](/blog/next-10#importing-css-from-third-party-react-components) * [Automatic Resolving of href](/blog/next-10#automatic-resolving-of-href) * [@next/codemod CLI](/blog/next-10#nextcodemod-cli) * [Blocking Fallback for getStaticPaths](/blog/next-10#blocking-fallback-for-getstaticpaths) [Read More](/blog/next-10) July 27th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) +3![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) [Next.js 9.5](/blog/next-9-5) We are excited today to introduce Next.js 9.5, featuring: * [Stable Incremental Static Regeneration](/blog/next-9-5#stable-incremental-static-regeneration) * [Customizable Base Path](/blog/next-9-5#customizable-base-path) * [Support for Rewrites, Redirects, and Headers](/blog/next-9-5#support-for-rewrites-redirects-and-headers) * [Optional Trailing Slash in URLs](/blog/next-9-5#optional-trailing-slash-in-urls) * [Persistent Caching for Page Bundles](/blog/next-9-5#persistent-caching-for-page-bundles) * [Fast Refresh Enhancements](/blog/next-9-5#fast-refresh-enhancements) * [Production React Profiling](/blog/next-9-5#production-react-profiling) * [Optional Catch All Routes](/blog/next-9-5#optional-catch-all-routes) * [Webpack 5 Support (beta)](/blog/next-9-5#webpack-5-support-beta) [Read More](/blog/next-9-5) May 11th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) +2![](/_next/image?url=%2Fstatic%2Fteam%2Flfades.jpg&w=48&q=75) [Next.js 9.4](/blog/next-9-4) We are excited today to introduce Next.js 9.4, featuring: * [Fast Refresh](/blog/next-9-4#fast-refresh) * [Incremental Static Regeneration (beta)](/blog/next-9-4#incremental-static-regeneration-beta) * [CMS Examples](/blog/next-9-4#cms-examples) * [New Environment Variables Support](/blog/next-9-4#new-environment-variables-support) * [Improved Built-in Fetch Support](/blog/next-9-4#improved-built-in-fetch-support) * [Integrated Web Vitals Reporting](/blog/next-9-4#integrated-web-vitals-reporting) * [Absolute Imports and Aliases](/blog/next-9-4#absolute-imports-and-aliases) * [Configurable Sass Support](/blog/next-9-4#configurable-sass-support) * [Improved Log Output](/blog/next-9-4#improved-log-output) [Read More](/blog/next-9-4) March 9th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) +2![](/_next/image?url=%2Fstatic%2Fteam%2Flfades.jpg&w=48&q=75) [Next.js 9.3](/blog/next-9-3) We are excited today to introduce Next.js 9.3, featuring: * [Next-gen Static Site Generation (SSG) Support](/blog/next-9-3#next-gen-static-site-generation-ssg-support) * [Preview Mode](/blog/next-9-3#preview-mode) * [Built-In Sass Support for Global Stylesheets](/blog/next-9-3#built-in-sass-support-for-global-stylesheets) * [Built-In Sass CSS Module Support for Component-Level Styles](/blog/next-9-3#built-in-sass-css-module-support-for-component-level-styles) * [Automatic Static Optimization for 404](/blog/next-9-3#automatic-static-optimization-for-404) * [32 kB Smaller Runtime](/blog/next-9-3#32-kb-smaller-runtime-15-kb-gzip) * [Next.js Community on GitHub Discussions](/blog/next-9-3#community) [Read More](/blog/next-9-3) January 15th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) +1![](/_next/image?url=%2Fstatic%2Fteam%2Flfades.jpg&w=48&q=75) [Next.js 9.2](/blog/next-9-2) We are excited today to introduce the production-ready Next.js 9.2, featuring: * [Built-In CSS Support for Global Stylesheets](/blog/next-9-2#built-in-css-support-for-global-stylesheets) * [Built-In CSS Module Support for Component-Level Styles](/blog/next-9-2#built-in-css-module-support-for-component-level-styles) * [Improved Code-Splitting Strategy](/blog/next-9-2#improved-code-splitting-strategy) * [Catch-All Dynamic Routes](/blog/next-9-2#catch-all-dynamic-routes) [Read More](/blog/next-9-2) January 9th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) +1![](/_next/image?url=%2Fstatic%2Fteam%2Flfades.jpg&w=48&q=75) [New Next.js Documentation](/blog/new-documentation) We're excited to announce the new Next.js documentation, featuring: * [Improved Content](/blog/new-documentation#improved-content) * [Search](/blog/new-documentation#search) * [API Reference](/blog/new-documentation#api-reference) [Read More](/blog/new-documentation) January 6th, 2020 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) +1![](/_next/image?url=%2Fstatic%2Fteam%2Flfades.jpg&w=48&q=75) [Next.js 9.1.7](/blog/next-9-1-7) [Next.js 9](/blog/next-9) was released six (6) months ago, followed by [Next.js 9.1](/blog/next-9-1) three (3) months ago. These two releases added very powerful new features to Next.js, without increasing our baseline client runtime size. Since then, we've focused heavily on refining and improving the framework as a whole: [9.1.1](https://github.com/vercel/next.js/releases/tag/v9.1.1), [9.1.2](https://github.com/vercel/next.js/releases/tag/v9.1.2), [9.1.3](https://github.com/vercel/next.js/releases/tag/v9.1.3), [9.1.4](https://github.com/vercel/next.js/releases/tag/v9.1.4), [9.1.5](https://github.com/vercel/next.js/releases/tag/v9.1.5), [9.1.6](https://github.com/vercel/next.js/releases/tag/v9.1.6), and [9.1.7](https://github.com/vercel/next.js/releases/tag/v9.1.7). Let's dive into what these releases have improved! * [3% – 8%+ Smaller Client-Side JavaScript Size](/blog/next-9-1-7#3--8-smaller-client-side-javascript-size) * [Redesigned Production Build CLI Output](/blog/next-9-1-7#redesigned-production-build-cli-output) * [New Built-In Polyfills: fetch(), URL, and Object.assign](/blog/next-9-1-7#new-built-in-polyfills-fetch-url-and-objectassign) * [Optimized Page Loading: Better FCP and TTI](/blog/next-9-1-7#optimized-page-loading-better-fcp-and-tti) * [Support for the Latest JavaScript Features](/blog/next-9-1-7#support-for-the-latest-javascript-features) * [Zero-Config Deployment Support for `next export` Applications](/blog/next-9-1-7#zero-config-deployment-support-for-next-export-applications) * [React Strict Mode Compliance and Opt-In](/blog/next-9-1-7#react-strict-mode-compliance-and-opt-in) * [Automated Testing against Nightly React Builds](/blog/next-9-1-7#automated-testing-against-nightly-react-builds) [Read More](/blog/next-9-1-7) October 9th, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Introducing Create Next App](/blog/create-next-app) We're delighted today to introduce the new Create Next App. Create Next App sets up a modern React application powered by Next.js in one command. [Read More](/blog/create-next-app) October 7th, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) +1![](/_next/image?url=%2Fstatic%2Fteam%2Flfades.jpg&w=48&q=75) [Next.js 9.1](/blog/next-9-1) Today, we are excited to announce Next.js 9.1 with `src` and `public` directory support. **New in This Release** * [`src` Directory Support](/blog/next-9-1#src-directory-support) * [`public` Directory Support](/blog/next-9-1#public-directory-support) **Previewing in This Release** * [Built-in CSS Support](/blog/next-9-1#built-in-css-support) * [Static Error Pages](/blog/next-9-1#static-error-pages) * [Module / Nomodule](/blog/next-9-1#module--nomodule) * [Improved Bundle Splitting](/blog/next-9-1#improved-bundle-splitting) [Read More](/blog/next-9-1) September 30th, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) +2![](/_next/image?url=%2Fstatic%2Fteam%2Flfades.jpg&w=48&q=75) [Next.js 9.0.7](/blog/next-9-0-7) Next.js 9.0 was released approximately two months ago. Since then, we’ve been busy with 7 smaller but quite important releases: [9.0.1](https://github.com/vercel/next.js/releases/tag/v9.0.1), [9.0.2](https://github.com/vercel/next.js/releases/tag/v9.0.2), [9.0.3](https://github.com/vercel/next.js/releases/tag/v9.0.3), [9.0.4](https://github.com/vercel/next.js/releases/tag/v9.0.4), [9.0.5](https://github.com/vercel/next.js/releases/tag/v9.0.5), [9.0.6](https://github.com/vercel/next.js/releases/tag/v9.0.6), and [9.0.7](https://github.com/vercel/next.js/releases/tag/v9.0.7). Let’s dive into what these releases have brought to your websites and applications, with absolutely no breaking changes. * [Improved Concurrency in Windows Environments](/blog/next-9-0-7#improved-concurrency-in-windows-environments) * [Gzip Compression by Default](/blog/next-9-0-7#gzip-compression-by-default) * [TypeScript Report on Active Pages Only](/blog/next-9-0-7#typescript-report-on-active-pages-only) * [Telemetry](/blog/next-9-0-7#telemetry) * [Improved next/head Element Tracking](/blog/next-9-0-7#improved-nexthead-element-tracking) * [Preventing Non-Pages in the Pages Directory](/blog/next-9-0-7#preventing-non-pages-in-the-pages-directory) * [Runtime Improvements](/blog/next-9-0-7#runtime-improvements) [Read More](/blog/next-9-0-7) July 8th, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) +3![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) [Next.js 9](/blog/next-9) Today, we're excited to announce Next.js 9 with TypeScript support, Dynamic Routing, API Routes, Automatic Static Optimization, and more! * [Built-in Zero-Config TypeScript Support](/blog/next-9#built-in-zero-config-typescript-support) * [File system-Based Dynamic Routing](/blog/next-9#dynamic-route-segments) * [Automatic Static Optimization](/blog/next-9#automatic-static-optimization) * [API Routes](/blog/next-9#api-routes) * [More Production Optimizations](/blog/next-9#production-optimizations) * [Improved DX](/blog/next-9#developer-experience-improvements) [Read More](/blog/next-9) April 16th, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) +2![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) [Next.js 8.1](/blog/next-8-1) Today, we're excited to announce we've extended the Next.js experience to authoring AMP pages. * [What is AMP](/blog/next-8-1#what-is-amp) * [AMP in Next.js](/blog/next-8-1#amp-in-nextjs) * [Hybrid AMP pages](/blog/next-8-1#hybrid-amp-pages) * [AMP-first pages](/blog/next-8-1#amp-first-pages) * [AMP Validation](/blog/next-8-1#amp-validation) [Read More](/blog/next-8-1) April 2nd, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fjj.jpg&w=48&q=75) +2![](/_next/image?url=%2Fstatic%2Fteam%2Ftimer.jpg&w=48&q=75) [Next.js 8.0.4](/blog/next-8-0-4) We are happy to introduce the production-ready Next.js 8.0.4: * [Build performance improvements](/blog/next-8-0-4#build-performance) * [Deterministic builds](/blog/next-8-0-4#build-performance) * [Smaller client runtime](/blog/next-8-0-4#smaller-runtime-footprint) * [Smaller serverless functions](/blog/next-8-0-4#smaller-runtime-footprint) * [Default viewport tag](/blog/next-8-0-4#default-viewport-meta-tag) * [Learning guide improvements](/blog/next-8-0-4#learning-guide-improvements) [Read More](/blog/next-8-0-4) March 28th, 2019 [Styling Next.js with Styled JSX](/blog/styling-next-with-styled-jsx) [Styled JSX](https://github.com/vercel/styled-jsx) is a CSS-in-JS library that allows you to write encapsulated and scoped CSS to style your components. The styles you introduce for one component won't affect other components, allowing you to add, change and delete styles without worrying about unintended side effects. [Read More](/blog/styling-next-with-styled-jsx) February 19th, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 8 Webpack Memory Improvements](/blog/webpack-memory) Recently [Next.js 8](/blog/next-8) was introduced. The release included a massive build-time memory usage reduction. This blog post will explore how we have helped optimize webpack for the community. [Read More](/blog/webpack-memory) February 11th, 2019 ![](/_next/image?url=%2Fstatic%2Fteam%2Fconnor.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fshu.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 8](/blog/next-8) We are proud today to introduce the production-ready Next.js 8, featuring: * [Serverless Next.js](/blog/next-8#serverless-nextjs) * [Massive build-time memory usage reduction](/blog/next-8#massive-build-time-memory-usage-reduction) * [Build-time environment configuration](/blog/next-8#build-time-environment-configuration) * [Prefetch performance improvements](/blog/next-8#prefetch-performance-improvements) * [Smaller initial HTML size](/blog/next-8#smaller-initial-html-size) * [Improved on-demand entries](/blog/next-8#improved-on-demand-entries) * [Faster port listening in development](/blog/next-8#faster-port-listening-in-development) * [Faster Static Export](/blog/next-8#faster-static-export) * [Head element deduplication](/blog/next-8#head-element-deduplication) * [New crossOrigin config option](/blog/next-8#new-crossorigin-config-option) * [Removed inline Javascript](/blog/next-8#removed-inline-javascript) * [Example of API Authentication](/blog/next-8#example-of-api-authentication) [Read More](/blog/next-8) September 19th, 2018 ![](/_next/image?url=%2Fstatic%2Fcollaborators%2Fgiuseppe.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Fshu.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 7](/blog/next-7) After 26 canary releases and 3.4 million downloads, we are proud to introduce the production-ready Next.js 7, featuring: * [DX improvements](#dx-improvements): 57% faster bootup, 42% faster re-compilation * [Better error reporting](#better-error-reporting-with-react-error-overlay) with [react-error-overlay](https://www.npmjs.com/package/react-error-overlay) * [Upgraded compilation pipeline](#webpack-4): [Webpack 4](#webpack-4) and [Babel 7](#babel-7) * [Standardized Dynamic Imports](#standardized-dynamic-imports) * [Static CDN support](#static-cdn-support) * [Smaller initial HTML payload](#smaller-initial-html-payload) * [React Context with SSR between App and Pages](#react-context-with-ssr-between-app-and-pages) [Read More](/blog/next-7) June 27th, 2018 ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 6.1](/blog/next-6-1) We are proud today to introduce the production-ready **Next.js 6.1**, featuring: * Increased hot reloading reliability * Codebase improvements * Next.js codemods [Read More](/blog/next-6-1) May 16th, 2018 ![](/_next/image?url=%2Fstatic%2Fteam%2Farunoda.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 6 and Nextjs.org](/blog/next-6) We are proud today to introduce the production-ready **Next.js 6**, featuring: * Zero-configuration static exports. No need for `next.config.js` by default * `_app.js`, an extension point that enables page transitions, error boundaries and more * Babel 7 and Fragment syntax `<>` support * Extended integration test suites with a strong focus on security * Flow annotations in the core codebase [Read More](/blog/next-6) March 26th, 2018 ![](/_next/image?url=%2Fstatic%2Fteam%2Farunoda.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 5.1: Faster Page Resolution, Environment Config & More](/blog/next-5-1) We are happy to introduce Next.js 5.1, which features support for environment configuration, phases, source maps, and new Next.js plugins. [Read More](/blog/next-5-1) February 5th, 2018 ![](/_next/image?url=%2Fstatic%2Fteam%2Farunoda.jpg&w=48&q=75) ![](/_next/image?url=%2Fstatic%2Fteam%2Ftim.jpg&w=48&q=75) [Next.js 5: Universal Webpack, CSS Imports, Plugins and Zones](/blog/next-5) We are very happy to introduce Next.js 5.0 to the world. It’s available on npm effective immediately. [Read More](/blog/next-5)
{ "contentLength": null, "etag": "W/\"34011cc946c279e968cc22fa4dbe22e4\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/
ran **May 23**. Check out the announcements. Vercel Ship 24 [Watch the Keynote](https://vercel.com/ship?utm_source=next_site&utm_medium=web&utm_campaign=vercel_ship&utm_content=next_site_home) Vercel Ship 24 ran **May 23**. Check out the announcements. [Watch the Keynote](https://vercel.com/ship?utm_source=next_site&utm_medium=web&utm_campaign=vercel_ship&utm_content=next_site_home) ![Next.js uwu logo by SAWARATSUKI](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1714730590%2Ffront%2Fnextjs%2Fuwu%2Fnext-uwu-logo.png&w=1080&q=75) The React Framework for the Web =============================== Used by some of the world's largest companies, Next.js enables you to create **high-quality web applications** with the power of React components. [Get Started](/docs)[Learn Next.js](/learn?utm_source=next-site&utm_medium=homepage-cta&utm_campaign=home) ▲ ~ npx create-next-app@latest What's in Next.js? ------------------ Everything you need to build great products on the web. [ Original 1440px 375px Built-in Optimizations Automatic Image, Font, and Script Optimizations for improved UX and Core Web Vitals. ](/docs/app/building-your-application/optimizing/images)[ Data Fetching Make your React component async and await your data. Next.js supports both server and client data fetching. ](/docs/app/building-your-application/data-fetching)[ Server Actions Run server code by calling a function. Skip the API. Then, easily revalidate cached data and update your UI in one network roundtrip. ](/docs/app/building-your-application/data-fetching/forms-and-mutations)[ Advanced Routing & Nested Layouts Create routes using the file system, including support for more advanced routing patterns and UI layouts. ](/docs/app/building-your-application/routing) [ Dynamic HTML Streaming Instantly stream UI from the server, integrated with the App Router and React Suspense. ](/docs/app/building-your-application/routing/loading-ui-and-streaming)[ CSS Support Style your application with your favorite tools, including support for CSS Modules, Tailwind CSS, and popular community libraries. ](/docs/app/building-your-application/styling)[ Route Handlers Build API endpoints to securely connect with third-party services for handling auth or listening for webhooks. ](/docs/app/building-your-application/routing/router-handlers)[ Middleware Take control of the incoming request. Use code to define routing and access rules for authentication, experimentation, and internationalization. ](/docs/app/building-your-application/routing/middleware) [ ![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-light.png&w=640&q=100)![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-dark.png&w=640&q=100) React Server Components Add components without sending additional client-side JavaScript. Built on the latest React features. ](/docs/getting-started/react-essentials)[ Client and Server Rendering Flexible rendering and caching options, including Incremental Static Regeneration (ISR), on a per-page level. ](/docs/app/building-your-application/rendering)[ Next.js 14 The power of full-stack to the frontend. Read the release notes. ](/blog/next-14) [ ![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-light.png&w=640&q=100)![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-dark.png&w=640&q=100) Built-in Optimizations Automatic Image, Font, and Script Optimizations for improved UX and Core Web Vitals. ](/docs/app/building-your-application/optimizing/images)[ ![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-light.png&w=640&q=100)![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-dark.png&w=640&q=100) React Server Components Add components without sending additional client-side JavaScript. Built on the latest React features. ](/docs/getting-started/react-essentials)[ Data Fetching Make your React component async and await your data. Next.js supports both server and client data fetching. ](/docs/app/building-your-application/data-fetching)[ Server Actions Run server code by calling a function. Skip the API. Then, easily revalidate cached data and update your UI in one network roundtrip. ](/docs/app/building-your-application/data-fetching/forms-and-mutations)[ Advanced Routing & Nested Layouts Create routes using the file system, including support for more advanced routing patterns and UI layouts. ](/docs/app/building-your-application/routing) [ Dynamic HTML Streaming Instantly stream UI from the server, integrated with the App Router and React Suspense. ](/docs/app/building-your-application/routing/loading-ui-and-streaming)[ CSS Support Style your application with your favorite tools, including support for CSS Modules, Tailwind CSS, and popular community libraries. ](/docs/app/building-your-application/styling)[ Route Handlers Build API endpoints to securely connect with third-party services for handling auth or listening for webhooks. ](/docs/app/building-your-application/routing/router-handlers)[ Middleware Take control of the incoming request. Use code to define routing and access rules for authentication, experimentation, and internationalization. ](/docs/app/building-your-application/routing/middleware)[ Client and Server Rendering Flexible rendering and caching options, including Incremental Static Regeneration (ISR), on a per-page level. ](/docs/app/building-your-application/rendering)[ Next.js 14 The power of full-stack to the frontend. Read the release notes. ](/blog/next-14) [ ![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-light.png&w=640&q=100)![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-dark.png&w=640&q=100) Built-in Optimizations Automatic Image, Font, and Script Optimizations for improved UX and Core Web Vitals. ](/docs/app/building-your-application/optimizing/images)[ Dynamic HTML Streaming Instantly stream UI from the server, integrated with the App Router and React Suspense. ](/docs/app/building-your-application/routing/loading-ui-and-streaming)[ ![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-light.png&w=640&q=100)![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-dark.png&w=640&q=100) React Server Components Add components without sending additional client-side JavaScript. Built on the latest React features. ](/docs/getting-started/react-essentials) [ Data Fetching Make your React component async and await your data. Next.js supports both server and client data fetching. ](/docs/app/building-your-application/data-fetching)[ Server Actions Run server code by calling a function. Skip the API. Then, easily revalidate cached data and update your UI in one network roundtrip. ](/docs/app/building-your-application/data-fetching/forms-and-mutations)[ Advanced Routing & Nested Layouts Create routes using the file system, including support for more advanced routing patterns and UI layouts. ](/docs/app/building-your-application/routing)[ CSS Support Style your application with your favorite tools, including support for CSS Modules, Tailwind CSS, and popular community libraries. ](/docs/app/building-your-application/styling)[ Route Handlers Build API endpoints to securely connect with third-party services for handling auth or listening for webhooks. ](/docs/app/building-your-application/routing/router-handlers)[ Middleware Take control of the incoming request. Use code to define routing and access rules for authentication, experimentation, and internationalization. ](/docs/app/building-your-application/routing/middleware)[ Client and Server Rendering Flexible rendering and caching options, including Incremental Static Regeneration (ISR), on a per-page level. ](/docs/app/building-your-application/rendering) [ Next.js 14 The power of full-stack to the frontend. Read the release notes. ](/blog/next-14) Built on a foundation of fast, production-grade tooling ------------------------------------------------------- ![](/icons/mobile-lines.svg) Powered By [ ![React Logo](/icons/react.svg) ReactThe library for web and native user interfaces. Next.js is built on the latest React features, including Server Components and Actions. ](https://react.dev)[ ![Turbopack Logo](/icons/turbopack.svg) TurbopackAn incremental bundler optimized for JavaScript and TypeScript, written in Rust ![Rust Logo](/icons/rust.svg), and built into Next.js. ](https://turbo.build)[ ![SWC Logo](/icons/swc.svg) Speedy Web CompilerAn extensible Rust ![Rust Logo](/icons/rust.svg) based platform for the next generation of fast developer tools, and can be used for both compilation and minification. ](https://swc.rs) Get started in seconds ---------------------- Deploy Next.js to Vercel StarterEcommerceBlogAIEdge FunctionsEdge ConfigPortfolioSaaSMulti-tenant AppsRealtime AppsDocumentationVirtual EventWeb3 Vercel is a frontend cloud from the creators of Next.js, making it easy to get started with Next.js quickly. Jumpstart your Next.js development with pre-built solutions from Vercel and our community. [Deploy a Template on Vercel](https://vercel.com/templates/next.js?utm_source=next-site&utm_medium=deploy-template-on-vercel-cta&utm_campaign=homepage-new) ![A Next.js app and a Serverless Function API.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122002%2Fnextjs%2Fshowcase%2Ftemplate-next-boilerplate.jpg&w=3840&q=75) Next.js Boilerplate A Next.js app and a Serverless Function API. ![An image gallery built on Next.js and Cloudinary.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122387%2Fnextjs%2Fshowcase%2Ftemplate-next-gallery.jpg&w=3840&q=75) Image Gallery Starter An image gallery built on Next.js and Cloudinary. ![An all-in-one starter kit for high-performance ecommerce sites.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122003%2Fnextjs%2Fshowcase%2Ftemplate-next-commerce.jpg&w=3840&q=75) Next.js Commerce An all-in-one starter kit for high-performance ecommerce sites. ![](/icons/divider.svg)![](/icons/divider-mobile.svg) The framework of choice when it matters --------------------------------------- [![Screenshot of Audible's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-audible.6063405a.png&w=828&q=75) Audible * * * ](/showcase)[![Screenshot of Sonos's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-sonos.a3dbc334.png&w=828&q=75) Sonos * * * ](/showcase) [![Screenshot of Twitch's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-twitch.4ed9ddb3.png&w=640&q=75) Twitch * * * ](/showcase) [![Screenshot of Notion's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-notion.2bd1f0c5.png&w=828&q=75) Notion * * * ](/showcase) [![Screenshot of Today's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-today.98d66e07.png&w=640&q=75) Today * * * ](/showcase)[![Screenshot of ProductHunt's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-ph.c43e26c6.png&w=640&q=75) ProductHunt * * * ](/showcase) [![Screenshot of Nike's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-nike.ae99d521.png&w=828&q=75) Nike * * * ](/showcase)[![Screenshot of Washington Post's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-wapo.2769ff64.png&w=828&q=75) Washington Post * * * ](/showcase) [![Screenshot of Sonos's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-sonos.a3dbc334.png&w=640&q=75) Sonos * * * ](/showcase)[![Screenshot of Audible's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-audible.6063405a.png&w=640&q=75) Audible * * * ](/showcase)[![Screenshot of Nike's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-nike.ae99d521.png&w=640&q=75) Nike * * * ](/showcase) [![Screenshot of Notion's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-notion.2bd1f0c5.png&w=640&q=75) Notion * * * ](/showcase)[![Screenshot of ProductHunt's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-ph.c43e26c6.png&w=640&q=75) ProductHunt * * * ](/showcase)[![Screenshot of Washington Post's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-wapo.2769ff64.png&w=640&q=75) Washington Post * * * ](/showcase) For **performance**, **efficiency** and **developer experience**. Next.js is trusted by some of the biggest names on the web. [View the Next.js Showcase](/showcase) Customer Testimonials --------------------- > ### “With Next.js at the helm of our headless tech stack, our developers can create features with velocity and speed, ultimately enabling users to create whatever, whenever they want to.” Tatiana Mac, Senior Software Engineer > ### “My favorite UX feedback from customers is: "How is the app so fast?" Because we’ve built on Next.js and Vercel since day one, our pages load in an instant, which is important when it comes to mission-critical software.” Fouad Matin, CEO > ### “Next.js has been a game-changer for our agency work and team collaboration. Its powerful features have allowed us to build high-performance websites quickly and efficiently like never before.” Daniel Lopes, Frontend Developer
{ "contentLength": null, "etag": "W/\"6cf2944589e9b377be2ef0f9101c0e9c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[API Reference](/docs/app/api-reference)Functions Functions ========= [ ### cookies API Reference for the cookies function. ](/docs/app/api-reference/functions/cookies)[ ### draftMode API Reference for the draftMode function. ](/docs/app/api-reference/functions/draft-mode)[ ### fetch API reference for the extended fetch function. ](/docs/app/api-reference/functions/fetch)[ ### generateImageMetadata Learn how to generate multiple images in a single Metadata API special file. ](/docs/app/api-reference/functions/generate-image-metadata)[ ### generateMetadata Learn how to add Metadata to your Next.js application for improved search engine optimization (SEO) and web shareability. ](/docs/app/api-reference/functions/generate-metadata)[ ### generateSitemaps Learn how to use the generateSiteMaps function to create multiple sitemaps for your application. ](/docs/app/api-reference/functions/generate-sitemaps)[ ### generateStaticParams API reference for the generateStaticParams function. ](/docs/app/api-reference/functions/generate-static-params)[ ### generateViewport API Reference for the generateViewport function. ](/docs/app/api-reference/functions/generate-viewport)[ ### headers API reference for the headers function. ](/docs/app/api-reference/functions/headers)[ ### ImageResponse API Reference for the ImageResponse constructor. ](/docs/app/api-reference/functions/image-response)[ ### NextRequest API Reference for NextRequest. ](/docs/app/api-reference/functions/next-request)[ ### NextResponse API Reference for NextResponse. ](/docs/app/api-reference/functions/next-response)[ ### notFound API Reference for the notFound function. ](/docs/app/api-reference/functions/not-found)[ ### permanentRedirect API Reference for the permanentRedirect function. ](/docs/app/api-reference/functions/permanentRedirect)[ ### redirect API Reference for the redirect function. ](/docs/app/api-reference/functions/redirect)[ ### revalidatePath API Reference for the revalidatePath function. ](/docs/app/api-reference/functions/revalidatePath)[ ### revalidateTag API Reference for the revalidateTag function. ](/docs/app/api-reference/functions/revalidateTag)[ ### unstable\_cache API Reference for the unstable\_cache function. ](/docs/app/api-reference/functions/unstable_cache)[ ### unstable\_noStore API Reference for the unstable\_noStore function. ](/docs/app/api-reference/functions/unstable_noStore)[ ### useParams API Reference for the useParams hook. ](/docs/app/api-reference/functions/use-params)[ ### usePathname API Reference for the usePathname hook. ](/docs/app/api-reference/functions/use-pathname)[ ### useReportWebVitals API Reference for the useReportWebVitals function. ](/docs/app/api-reference/functions/use-report-web-vitals)[ ### useRouter API reference for the useRouter hook. ](/docs/app/api-reference/functions/use-router)[ ### useSearchParams API Reference for the useSearchParams hook. ](/docs/app/api-reference/functions/use-search-params)[ ### useSelectedLayoutSegment API Reference for the useSelectedLayoutSegment hook. ](/docs/app/api-reference/functions/use-selected-layout-segment)[ ### useSelectedLayoutSegments API Reference for the useSelectedLayoutSegments hook. ](/docs/app/api-reference/functions/use-selected-layout-segments)[ ### userAgent The userAgent helper extends the Web Request API with additional properties and methods to interact with the user agent object from the request. ](/docs/app/api-reference/functions/userAgent) [Previous sitemap.xml ](/docs/app/api-reference/file-conventions/metadata/sitemap) [Next cookies ](/docs/app/api-reference/functions/cookies) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"34011cc946c279e968cc22fa4dbe22e4\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/?uwu=true
ran **May 23**. Check out the announcements. Vercel Ship 24 [Watch the Keynote](https://vercel.com/ship?utm_source=next_site&utm_medium=web&utm_campaign=vercel_ship&utm_content=next_site_home) Vercel Ship 24 ran **May 23**. Check out the announcements. [Watch the Keynote](https://vercel.com/ship?utm_source=next_site&utm_medium=web&utm_campaign=vercel_ship&utm_content=next_site_home) ![Next.js uwu logo by SAWARATSUKI](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1714730590%2Ffront%2Fnextjs%2Fuwu%2Fnext-uwu-logo.png&w=1080&q=75) The React Framework for the Web =============================== Used by some of the world's largest companies, Next.js enables you to create **high-quality web applications** with the power of React components. [Get Started](/docs)[Learn Next.js](/learn?utm_source=next-site&utm_medium=homepage-cta&utm_campaign=home) ▲ ~ npx create-next-app@latest What's in Next.js? ------------------ Everything you need to build great products on the web. [ Original 1440px 375px Built-in Optimizations Automatic Image, Font, and Script Optimizations for improved UX and Core Web Vitals. ](/docs/app/building-your-application/optimizing/images)[ Data Fetching Make your React component async and await your data. Next.js supports both server and client data fetching. ](/docs/app/building-your-application/data-fetching)[ Server Actions Run server code by calling a function. Skip the API. Then, easily revalidate cached data and update your UI in one network roundtrip. ](/docs/app/building-your-application/data-fetching/forms-and-mutations)[ Advanced Routing & Nested Layouts Create routes using the file system, including support for more advanced routing patterns and UI layouts. ](/docs/app/building-your-application/routing) [ Dynamic HTML Streaming Instantly stream UI from the server, integrated with the App Router and React Suspense. ](/docs/app/building-your-application/routing/loading-ui-and-streaming)[ CSS Support Style your application with your favorite tools, including support for CSS Modules, Tailwind CSS, and popular community libraries. ](/docs/app/building-your-application/styling)[ Route Handlers Build API endpoints to securely connect with third-party services for handling auth or listening for webhooks. ](/docs/app/building-your-application/routing/router-handlers)[ Middleware Take control of the incoming request. Use code to define routing and access rules for authentication, experimentation, and internationalization. ](/docs/app/building-your-application/routing/middleware) [ ![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-light.png&w=640&q=100)![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-dark.png&w=640&q=100) React Server Components Add components without sending additional client-side JavaScript. Built on the latest React features. ](/docs/getting-started/react-essentials)[ Client and Server Rendering Flexible rendering and caching options, including Incremental Static Regeneration (ISR), on a per-page level. ](/docs/app/building-your-application/rendering)[ Next.js 14 The power of full-stack to the frontend. Read the release notes. ](/blog/next-14) [ ![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-light.png&w=640&q=100)![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-dark.png&w=640&q=100) Built-in Optimizations Automatic Image, Font, and Script Optimizations for improved UX and Core Web Vitals. ](/docs/app/building-your-application/optimizing/images)[ ![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-light.png&w=640&q=100)![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-dark.png&w=640&q=100) React Server Components Add components without sending additional client-side JavaScript. Built on the latest React features. ](/docs/getting-started/react-essentials)[ Data Fetching Make your React component async and await your data. Next.js supports both server and client data fetching. ](/docs/app/building-your-application/data-fetching)[ Server Actions Run server code by calling a function. Skip the API. Then, easily revalidate cached data and update your UI in one network roundtrip. ](/docs/app/building-your-application/data-fetching/forms-and-mutations)[ Advanced Routing & Nested Layouts Create routes using the file system, including support for more advanced routing patterns and UI layouts. ](/docs/app/building-your-application/routing) [ Dynamic HTML Streaming Instantly stream UI from the server, integrated with the App Router and React Suspense. ](/docs/app/building-your-application/routing/loading-ui-and-streaming)[ CSS Support Style your application with your favorite tools, including support for CSS Modules, Tailwind CSS, and popular community libraries. ](/docs/app/building-your-application/styling)[ Route Handlers Build API endpoints to securely connect with third-party services for handling auth or listening for webhooks. ](/docs/app/building-your-application/routing/router-handlers)[ Middleware Take control of the incoming request. Use code to define routing and access rules for authentication, experimentation, and internationalization. ](/docs/app/building-your-application/routing/middleware)[ Client and Server Rendering Flexible rendering and caching options, including Incremental Static Regeneration (ISR), on a per-page level. ](/docs/app/building-your-application/rendering)[ Next.js 14 The power of full-stack to the frontend. Read the release notes. ](/blog/next-14) [ ![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-light.png&w=640&q=100)![Three abstract images are resized at three different sizes and stacked on top of each other](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fwindows-dark.png&w=640&q=100) Built-in Optimizations Automatic Image, Font, and Script Optimizations for improved UX and Core Web Vitals. ](/docs/app/building-your-application/optimizing/images)[ Dynamic HTML Streaming Instantly stream UI from the server, integrated with the App Router and React Suspense. ](/docs/app/building-your-application/routing/loading-ui-and-streaming)[ ![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-light.png&w=640&q=100)![A tree structure of 3D spheres are connected by lines](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fnextjs%2Fspheres-dark.png&w=640&q=100) React Server Components Add components without sending additional client-side JavaScript. Built on the latest React features. ](/docs/getting-started/react-essentials) [ Data Fetching Make your React component async and await your data. Next.js supports both server and client data fetching. ](/docs/app/building-your-application/data-fetching)[ Server Actions Run server code by calling a function. Skip the API. Then, easily revalidate cached data and update your UI in one network roundtrip. ](/docs/app/building-your-application/data-fetching/forms-and-mutations)[ Advanced Routing & Nested Layouts Create routes using the file system, including support for more advanced routing patterns and UI layouts. ](/docs/app/building-your-application/routing)[ CSS Support Style your application with your favorite tools, including support for CSS Modules, Tailwind CSS, and popular community libraries. ](/docs/app/building-your-application/styling)[ Route Handlers Build API endpoints to securely connect with third-party services for handling auth or listening for webhooks. ](/docs/app/building-your-application/routing/router-handlers)[ Middleware Take control of the incoming request. Use code to define routing and access rules for authentication, experimentation, and internationalization. ](/docs/app/building-your-application/routing/middleware)[ Client and Server Rendering Flexible rendering and caching options, including Incremental Static Regeneration (ISR), on a per-page level. ](/docs/app/building-your-application/rendering) [ Next.js 14 The power of full-stack to the frontend. Read the release notes. ](/blog/next-14) Built on a foundation of fast, production-grade tooling ------------------------------------------------------- ![](/icons/mobile-lines.svg) Powered By [ ![React Logo](/icons/react.svg) ReactThe library for web and native user interfaces. Next.js is built on the latest React features, including Server Components and Actions. ](https://react.dev)[ ![Turbopack Logo](/icons/turbopack.svg) TurbopackAn incremental bundler optimized for JavaScript and TypeScript, written in Rust ![Rust Logo](/icons/rust.svg), and built into Next.js. ](https://turbo.build)[ ![SWC Logo](/icons/swc.svg) Speedy Web CompilerAn extensible Rust ![Rust Logo](/icons/rust.svg) based platform for the next generation of fast developer tools, and can be used for both compilation and minification. ](https://swc.rs) Get started in seconds ---------------------- Deploy Next.js to Vercel StarterEcommerceBlogAIEdge FunctionsEdge ConfigPortfolioSaaSMulti-tenant AppsRealtime AppsDocumentationVirtual EventWeb3 Vercel is a frontend cloud from the creators of Next.js, making it easy to get started with Next.js quickly. Jumpstart your Next.js development with pre-built solutions from Vercel and our community. [Deploy a Template on Vercel](https://vercel.com/templates/next.js?utm_source=next-site&utm_medium=deploy-template-on-vercel-cta&utm_campaign=homepage-new) ![A Next.js app and a Serverless Function API.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122002%2Fnextjs%2Fshowcase%2Ftemplate-next-boilerplate.jpg&w=3840&q=75) Next.js Boilerplate A Next.js app and a Serverless Function API. ![An image gallery built on Next.js and Cloudinary.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122387%2Fnextjs%2Fshowcase%2Ftemplate-next-gallery.jpg&w=3840&q=75) Image Gallery Starter An image gallery built on Next.js and Cloudinary. ![An all-in-one starter kit for high-performance ecommerce sites.](/_next/image?url=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Fv1677122003%2Fnextjs%2Fshowcase%2Ftemplate-next-commerce.jpg&w=3840&q=75) Next.js Commerce An all-in-one starter kit for high-performance ecommerce sites. ![](/icons/divider.svg)![](/icons/divider-mobile.svg) The framework of choice when it matters --------------------------------------- [![Screenshot of Audible's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-audible.6063405a.png&w=828&q=75) Audible * * * ](/showcase)[![Screenshot of Sonos's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-sonos.a3dbc334.png&w=828&q=75) Sonos * * * ](/showcase) [![Screenshot of Twitch's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-twitch.4ed9ddb3.png&w=640&q=75) Twitch * * * ](/showcase) [![Screenshot of Notion's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-notion.2bd1f0c5.png&w=828&q=75) Notion * * * ](/showcase) [![Screenshot of Today's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-today.98d66e07.png&w=640&q=75) Today * * * ](/showcase)[![Screenshot of ProductHunt's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-ph.c43e26c6.png&w=640&q=75) ProductHunt * * * ](/showcase) [![Screenshot of Nike's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-nike.ae99d521.png&w=828&q=75) Nike * * * ](/showcase)[![Screenshot of Washington Post's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-wapo.2769ff64.png&w=828&q=75) Washington Post * * * ](/showcase) [![Screenshot of Sonos's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-sonos.a3dbc334.png&w=640&q=75) Sonos * * * ](/showcase)[![Screenshot of Audible's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-audible.6063405a.png&w=640&q=75) Audible * * * ](/showcase)[![Screenshot of Nike's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-nike.ae99d521.png&w=640&q=75) Nike * * * ](/showcase) [![Screenshot of Notion's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-notion.2bd1f0c5.png&w=640&q=75) Notion * * * ](/showcase)[![Screenshot of ProductHunt's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-ph.c43e26c6.png&w=640&q=75) ProductHunt * * * ](/showcase)[![Screenshot of Washington Post's website](/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpreview-wapo.2769ff64.png&w=640&q=75) Washington Post * * * ](/showcase) For **performance**, **efficiency** and **developer experience**. Next.js is trusted by some of the biggest names on the web. [View the Next.js Showcase](/showcase) Customer Testimonials --------------------- > ### “With Next.js at the helm of our headless tech stack, our developers can create features with velocity and speed, ultimately enabling users to create whatever, whenever they want to.” Tatiana Mac, Senior Software Engineer > ### “My favorite UX feedback from customers is: "How is the app so fast?" Because we’ve built on Next.js and Vercel since day one, our pages load in an instant, which is important when it comes to mission-critical software.” Fouad Matin, CEO > ### “Next.js has been a game-changer for our agency work and team collaboration. Its powerful features have allowed us to build high-performance websites quickly and efficiently like never before.” Daniel Lopes, Frontend Developer
{ "contentLength": null, "etag": "W/\"769d3ce6f9693fb26a2cb6f889ffc5d7\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [ Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Fetching Data on the Server with fetch](#fetching-data-on-the-server-with-fetch) * [Caching Data](#caching-data) * [Revalidating Data](#revalidating-data) * [Time-based Revalidation](#time-based-revalidation) * [On-demand Revalidation](#on-demand-revalidation) * [Error handling and revalidation](#error-handling-and-revalidation) * [Opting out of Data Caching](#opting-out-of-data-caching) * [Individual fetch Requests](#individual-fetch-requests) * [Multiple fetch Requests](#multiple-fetch-requests) * [Fetching data on the Server with third-party libraries](#fetching-data-on-the-server-with-third-party-libraries) * [Example](#example) * [Fetching Data on the Client with Route Handlers](#fetching-data-on-the-client-with-route-handlers) * [Fetching Data on the Client with third-party libraries](#fetching-data-on-the-client-with-third-party-libraries) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Data Fetching](/docs/app/building-your-application/data-fetching)Fetching, Caching, and Revalidating Data Fetching, Caching, and Revalidating ======================================== Data fetching is a core part of any application. This page goes through how you can fetch, cache, and revalidate data in React and Next.js. There are four ways you can fetch data: 1. [On the server, with `fetch`](#fetching-data-on-the-server-with-fetch) 2. [On the server, with third-party libraries](#fetching-data-on-the-server-with-third-party-libraries) 3. [On the client, via a Route Handler](#fetching-data-on-the-client-with-route-handlers) 4. [On the client, with third-party libraries](#fetching-data-on-the-client-with-route-handlers). [Fetching Data on the Server with `fetch`](#fetching-data-on-the-server-with-fetch) ----------------------------------------------------------------------------------- Next.js extends the native [`fetch` Web API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow you to configure the [caching](#caching-data) and [revalidating](#revalidating-data) behavior for each fetch request on the server. React extends `fetch` to automatically [memoize](/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed) fetch requests while rendering a React component tree. You can use `fetch` with `async`/`await` in Server Components, in [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). For example: app/page.tsx TypeScript JavaScriptTypeScript async function getData() { const res = await fetch('https://api.example.com/...') // The return value is *not* serialized // You can return Date, Map, Set, etc. if (!res.ok) { // This will activate the closest `error.js` Error Boundary throw new Error('Failed to fetch data') } return res.json() } export default async function Page() { const data = await getData() return <main></main> } > **Good to know**: > > * Next.js provides helpful functions you may need when fetching data in Server Components such as [`cookies`](/docs/app/api-reference/functions/cookies) and [`headers`](/docs/app/api-reference/functions/headers). These will cause the route to be dynamically rendered as they rely on request time information. > * In Route handlers, `fetch` requests are not memoized as Route Handlers are not part of the React component tree. > * In [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations), `fetch` requests are not cached (defaults `cache: no-store`). > * To use `async`/`await` in a Server Component with TypeScript, you'll need to use TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher. ### [Caching Data](#caching-data) Caching stores data so it doesn't need to be re-fetched from your data source on every request. By default, Next.js automatically caches the returned values of `fetch` in the [Data Cache](/docs/app/building-your-application/caching#data-cache) on the server. This means that the data can be fetched at build time or request time, cached, and reused on each data request. // 'force-cache' is the default, and can be omitted fetch('https://...', { cache: 'force-cache' }) However, there are exceptions, `fetch` requests are not cached when: * Used inside a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). * Used inside a [Route Handler](/docs/app/building-your-application/routing/route-handlers) that uses the `POST` method. > **What is the Data Cache?** > > The Data Cache is a persistent [HTTP cache](https://developer.mozilla.org/docs/Web/HTTP/Caching). Depending on your platform, the cache can scale automatically and be [shared across multiple regions](https://vercel.com/docs/infrastructure/data-cache). > > Learn more about the [Data Cache](/docs/app/building-your-application/caching#data-cache). ### [Revalidating Data](#revalidating-data) Revalidation is the process of purging the Data Cache and re-fetching the latest data. This is useful when your data changes and you want to ensure you show the latest information. Cached data can be revalidated in two ways: * **Time-based revalidation**: Automatically revalidate data after a certain amount of time has passed. This is useful for data that changes infrequently and freshness is not as critical. * **On-demand revalidation**: Manually revalidate data based on an event (e.g. form submission). On-demand revalidation can use a tag-based or path-based approach to revalidate groups of data at once. This is useful when you want to ensure the latest data is shown as soon as possible (e.g. when content from your headless CMS is updated). #### [Time-based Revalidation](#time-based-revalidation) To revalidate data at a timed interval, you can use the `next.revalidate` option of `fetch` to set the cache lifetime of a resource (in seconds). fetch('https://...', { next: { revalidate: 3600 } }) Alternatively, to revalidate all `fetch` requests in a route segment, you can use the [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config). layout.js | page.js export const revalidate = 3600 // revalidate at most every hour If you have multiple fetch requests in a statically rendered route, and each has a different revalidation frequency. The lowest time will be used for all requests. For dynamically rendered routes, each `fetch` request will be revalidated independently. Learn more about [time-based revalidation](/docs/app/building-your-application/caching#time-based-revalidation). #### [On-demand Revalidation](#on-demand-revalidation) Data can be revalidated on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)) inside a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). Next.js has a cache tagging system for invalidating `fetch` requests across routes. 1. When using `fetch`, you have the option to tag cache entries with one or more tags. 2. Then, you can call `revalidateTag` to revalidate all entries associated with that tag. For example, the following `fetch` request adds the cache tag `collection`: app/page.tsx TypeScript JavaScriptTypeScript export default async function Page() { const res = await fetch('https://...', { next: { tags: ['collection'] } }) const data = await res.json() // ... } You can then revalidate this `fetch` call tagged with `collection` by calling `revalidateTag` in a Server Action: app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { revalidateTag } from 'next/cache' export default async function action() { revalidateTag('collection') } Learn more about [on-demand revalidation](/docs/app/building-your-application/caching#on-demand-revalidation). #### [Error handling and revalidation](#error-handling-and-revalidation) If an error is thrown while attempting to revalidate data, the last successfully generated data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data. ### [Opting out of Data Caching](#opting-out-of-data-caching) `fetch` requests are **not** cached if: * The `cache: 'no-store'` is added to `fetch` requests. * The `revalidate: 0` option is added to individual `fetch` requests. * The `fetch` request is inside a Router Handler that uses the `POST` method. * The `fetch` request comes after the usage of `headers` or `cookies`. * The `const dynamic = 'force-dynamic'` route segment option is used. * The `fetchCache` route segment option is configured to skip cache by default. * The `fetch` request uses `Authorization` or `Cookie` headers and there's an uncached request above it in the component tree. #### [Individual `fetch` Requests](#individual-fetch-requests) To opt out of caching for individual `fetch` requests, you can set the `cache` option in `fetch` to `'no-store'`. This will fetch data dynamically, on every request. layout.js | page.js fetch('https://...', { cache: 'no-store' }) View all the available `cache` options in the [`fetch` API reference](/docs/app/api-reference/functions/fetch). #### [Multiple `fetch` Requests](#multiple-fetch-requests) If you have multiple `fetch` requests in a route segment (e.g. a Layout or Page), you can configure the caching behavior of all data requests in the segment using the [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config). However, we recommend configuring the caching behavior of each `fetch` request individually. This gives you more granular control over the caching behavior. [Fetching data on the Server with third-party libraries](#fetching-data-on-the-server-with-third-party-libraries) ----------------------------------------------------------------------------------------------------------------- In cases where you're using a third-party library that doesn't support or expose `fetch` (for example, a database, CMS, or ORM client), you can configure the caching and revalidating behavior of those requests using the [Route Segment Config Option](/docs/app/api-reference/file-conventions/route-segment-config) and React's `cache` function. Whether the data is cached or not will depend on whether the route segment is [statically or dynamically rendered](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies). If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment. If the segment is dynamic, the output of the request will _not_ be cached and will be re-fetched on every request when the segment is rendered. You can also use the experimental [`unstable_cache` API](/docs/app/api-reference/functions/unstable_cache). ### [Example](#example) In the example below: * The React `cache` function is used to [memoize](/docs/app/building-your-application/caching#request-memoization) data requests. * The `revalidate` option is set to `3600` in the Layout and Page segments, meaning the data will be cached and revalidated at most every hour. app/utils.ts TypeScript JavaScriptTypeScript import { cache } from 'react' export const getItem = cache(async (id: string) => { const item = await db.item.findUnique({ id }) return item }) Although the `getItem` function is called twice, only one query will be made to the database. app/item/\[id\]/layout.tsx TypeScript JavaScriptTypeScript import { getItem } from '@/utils/get-item' export const revalidate = 3600 // revalidate the data at most every hour export default async function Layout({ params: { id }, }: { params: { id: string } }) { const item = await getItem(id) // ... } app/item/\[id\]/page.tsx TypeScript JavaScriptTypeScript import { getItem } from '@/utils/get-item' export const revalidate = 3600 // revalidate the data at most every hour export default async function Page({ params: { id }, }: { params: { id: string } }) { const item = await getItem(id) // ... } [Fetching Data on the Client with Route Handlers](#fetching-data-on-the-client-with-route-handlers) --------------------------------------------------------------------------------------------------- If you need to fetch data in a client component, you can call a [Route Handler](/docs/app/building-your-application/routing/route-handlers) from the client. Route Handlers execute on the server and return the data to the client. This is useful when you don't want to expose sensitive information to the client, such as API tokens. See the [Route Handler](/docs/app/building-your-application/routing/route-handlers) documentation for examples. > **Server Components and Route Handlers** > > Since Server Components render on the server, you don't need to call a Route Handler from a Server Component to fetch data. Instead, you can fetch the data directly inside the Server Component. [Fetching Data on the Client with third-party libraries](#fetching-data-on-the-client-with-third-party-libraries) ----------------------------------------------------------------------------------------------------------------- You can also fetch data on the client using a third-party library such as [SWR](https://swr.vercel.app/) or [TanStack Query](https://tanstack.com/query/latest). These libraries provide their own APIs for memoizing requests, caching, revalidating, and mutating data. > **Future APIs**: > > `use` is a React function that **accepts and handles a promise** returned by a function. Wrapping `fetch` in `use` is currently **not** recommended in Client Components and may trigger multiple re-renders. Learn more about `use` in the [React docs](https://react.dev/reference/react/use). [Previous Data Fetching ](/docs/app/building-your-application/data-fetching) [Next Server Actions and Mutations ](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"bcf6ce1c0dba916b2c235846790e2319\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [ Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Convention](#convention) * [Server Components](#server-components) * [Client Components](#client-components) * [Behavior](#behavior) * [Examples](#examples) * [Forms](#forms) * [Passing Additional Arguments](#passing-additional-arguments) * [Pending states](#pending-states) * [Server-side validation and error handling](#server-side-validation-and-error-handling) * [Optimistic updates](#optimistic-updates) * [Nested elements](#nested-elements) * [Programmatic form submission](#programmatic-form-submission) * [Non-form Elements](#non-form-elements) * [Event Handlers](#event-handlers) * [useEffect](#useeffect) * [Error Handling](#error-handling) * [Revalidating data](#revalidating-data) * [Redirecting](#redirecting) * [Cookies](#cookies) * [Security](#security) * [Authentication and authorization](#authentication-and-authorization) * [Closures and encryption](#closures-and-encryption) * [Overwriting encryption keys (advanced)](#overwriting-encryption-keys-advanced) * [Allowed origins (advanced)](#allowed-origins-advanced) * [Additional resources](#additional-resources) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/02-data-fetching/02-server-actions-and-mutations.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Data Fetching](/docs/app/building-your-application/data-fetching)Server Actions and Mutations Server Actions and Mutations ============================ Server Actions are **asynchronous functions** that are executed on the server. They can be used in Server and Client Components to handle form submissions and data mutations in Next.js applications. > **🎥 Watch:** Learn more about forms and mutations with Server Actions → [YouTube (10 minutes)](https://youtu.be/dDpZfOQBMaU?si=cJZHlUu_jFhCzHUg). [Convention](#convention) ------------------------- A Server Action can be defined with the React [`"use server"`](https://react.dev/reference/react/use-server) directive. You can place the directive at the top of an `async` function to mark the function as a Server Action, or at the top of a separate file to mark all exports of that file as Server Actions. ### [Server Components](#server-components) Server Components can use the inline function level or module level `"use server"` directive. To inline a Server Action, add `"use server"` to the top of the function body: app/page.tsx TypeScript JavaScriptTypeScript // Server Component export default function Page() { // Server Action async function create() { 'use server' // ... } return ( // ... ) } ### [Client Components](#client-components) Client Components can only import actions that use the module-level `"use server"` directive. To call a Server Action in a Client Component, create a new file and add the `"use server"` directive at the top of it. All functions within the file will be marked as Server Actions that can be reused in both Client and Server Components: app/actions.ts TypeScript JavaScriptTypeScript 'use server' export async function create() { // ... } app/ui/button.tsx TypeScript JavaScriptTypeScript import { create } from '@/app/actions' export function Button() { return ( // ... ) } You can also pass a Server Action to a Client Component as a prop: <ClientComponent updateItem={updateItem} /> app/client-component.jsx 'use client' export default function ClientComponent({ updateItem }) { return <form action={updateItem}>{/* ... */}</form> } [Behavior](#behavior) --------------------- * Server actions can be invoked using the `action` attribute in a [`<form>` element](#forms): * Server Components support progressive enhancement by default, meaning the form will be submitted even if JavaScript hasn't loaded yet or is disabled. * In Client Components, forms invoking Server Actions will queue submissions if JavaScript isn't loaded yet, prioritizing client hydration. * After hydration, the browser does not refresh on form submission. * Server Actions are not limited to `<form>` and can be invoked from event handlers, `useEffect`, third-party libraries, and other form elements like `<button>`. * Server Actions integrate with the Next.js [caching and revalidation](/docs/app/building-your-application/caching) architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip. * Behind the scenes, actions use the `POST` method, and only this HTTP method can invoke them. * The arguments and return value of Server Actions must be serializable by React. See the React docs for a list of [serializable arguments and values](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values). * Server Actions are functions. This means they can be reused anywhere in your application. * Server Actions inherit the [runtime](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) from the page or layout they are used on. * Server Actions inherit the [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) from the page or layout they are used on, including fields like `maxDuration`. [Examples](#examples) --------------------- ### [Forms](#forms) React extends the HTML [`<form>`](https://developer.mozilla.org/docs/Web/HTML/Element/form) element to allow Server Actions to be invoked with the `action` prop. When invoked in a form, the action automatically receives the [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData/FormData) object. You don't need to use React `useState` to manage fields, instead, you can extract the data using the native [`FormData` methods](https://developer.mozilla.org/en-US/docs/Web/API/FormData#instance_methods): app/invoices/page.tsx TypeScript JavaScriptTypeScript export default function Page() { async function createInvoice(formData: FormData) { 'use server' const rawFormData = { customerId: formData.get('customerId'), amount: formData.get('amount'), status: formData.get('status'), } // mutate data // revalidate cache } return <form action={createInvoice}>...</form> } > **Good to know:** > > * Example: [Form with Loading & Error States](https://github.com/vercel/next.js/tree/canary/examples/next-forms) > * When working with forms that have many fields, you may want to consider using the [`entries()`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries) method with JavaScript's [`Object.fromEntries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries). For example: `const rawFormData = Object.fromEntries(formData)`. One thing to note is that the `formData` will include additional `$ACTION_` properties. > * See [React `<form>` documentation](https://react.dev/reference/react-dom/components/form#handle-form-submission-with-a-server-action) to learn more. #### [Passing Additional Arguments](#passing-additional-arguments) You can pass additional arguments to a Server Action using the JavaScript `bind` method. app/client-component.tsx TypeScript JavaScriptTypeScript 'use client' import { updateUser } from './actions' export function UserProfile({ userId }: { userId: string }) { const updateUserWithId = updateUser.bind(null, userId) return ( <form action={updateUserWithId}> <input type="text" name="name" /> <button type="submit">Update User Name</button> </form> ) } The Server Action will receive the `userId` argument, in addition to the form data: app/actions.js 'use server' export async function updateUser(userId, formData) { // ... } > **Good to know**: > > * An alternative is to pass arguments as hidden input fields in the form (e.g. `<input type="hidden" name="userId" value={userId} />`). However, the value will be part of the rendered HTML and will not be encoded. > * `.bind` works in both Server and Client Components. It also supports progressive enhancement. #### [Pending states](#pending-states) You can use the React [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus) hook to show a pending state while the form is being submitted. * `useFormStatus` returns the status for a specific `<form>`, so it **must be defined as a child of the `<form>` element**. * `useFormStatus` is a React hook and therefore must be used in a Client Component. app/submit-button.tsx TypeScript JavaScriptTypeScript 'use client' import { useFormStatus } from 'react-dom' export function SubmitButton() { const { pending } = useFormStatus() return ( <button type="submit" disabled={pending}> Add </button> ) } `<SubmitButton />` can then be nested in any form: app/page.tsx TypeScript JavaScriptTypeScript import { SubmitButton } from '@/app/submit-button' import { createItem } from '@/app/actions' // Server Component export default async function Home() { return ( <form action={createItem}> <input type="text" name="field-name" /> <SubmitButton /> </form> ) } #### [Server-side validation and error handling](#server-side-validation-and-error-handling) We recommend using HTML validation like `required` and `type="email"` for basic client-side form validation. For more advanced server-side validation, you can use a library like [zod](https://zod.dev/) to validate the form fields before mutating the data: app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { z } from 'zod' const schema = z.object({ email: z.string({ invalid_type_error: 'Invalid Email', }), }) export default async function createUser(formData: FormData) { const validatedFields = schema.safeParse({ email: formData.get('email'), }) // Return early if the form data is invalid if (!validatedFields.success) { return { errors: validatedFields.error.flatten().fieldErrors, } } // Mutate data } Once the fields have been validated on the server, you can return a serializable object in your action and use the React [`useFormState`](https://react.dev/reference/react-dom/hooks/useFormState) hook to show a message to the user. * By passing the action to `useFormState`, the action's function signature changes to receive a new `prevState` or `initialState` parameter as its first argument. * `useFormState` is a React hook and therefore must be used in a Client Component. app/actions.ts TypeScript JavaScriptTypeScript 'use server' export async function createUser(prevState: any, formData: FormData) { // ... return { message: 'Please enter a valid email', } } Then, you can pass your action to the `useFormState` hook and use the returned `state` to display an error message. app/ui/signup.tsx TypeScript JavaScriptTypeScript 'use client' import { useFormState } from 'react-dom' import { createUser } from '@/app/actions' const initialState = { message: '', } export function Signup() { const [state, formAction] = useFormState(createUser, initialState) return ( <form action={formAction}> <label htmlFor="email">Email</label> <input type="text" id="email" name="email" required /> {/* ... */} <p aria-live="polite" className="sr-only"> {state?.message} </p> <button>Sign up</button> </form> ) } > **Good to know:** > > * Before mutating data, you should always ensure a user is also authorized to perform the action. See [Authentication and Authorization](#authentication-and-authorization). #### [Optimistic updates](#optimistic-updates) You can use the React [`useOptimistic`](https://react.dev/reference/react/useOptimistic) hook to optimistically update the UI before the Server Action finishes, rather than waiting for the response: app/page.tsx TypeScript JavaScriptTypeScript 'use client' import { useOptimistic } from 'react' import { send } from './actions' type Message = { message: string } export function Thread({ messages }: { messages: Message[] }) { const [optimisticMessages, addOptimisticMessage] = useOptimistic< Message[], string >(messages, (state, newMessage) => [...state, { message: newMessage }]) return ( <div> {optimisticMessages.map((m, k) => ( <div key={k}>{m.message}</div> ))} <form action={async (formData: FormData) => { const message = formData.get('message') addOptimisticMessage(message) await send(message) }} > <input type="text" name="message" /> <button type="submit">Send</button> </form> </div> ) } #### [Nested elements](#nested-elements) You can invoke a Server Action in elements nested inside `<form>` such as `<button>`, `<input type="submit">`, and `<input type="image">`. These elements accept the `formAction` prop or [event handlers](#event-handlers). This is useful in cases where you want to call multiple server actions within a form. For example, you can create a specific `<button>` element for saving a post draft in addition to publishing it. See the [React `<form>` docs](https://react.dev/reference/react-dom/components/form#handling-multiple-submission-types) for more information. #### [Programmatic form submission](#programmatic-form-submission) You can trigger a form submission using the [`requestSubmit()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit) method. For example, when the user presses `⌘` + `Enter`, you can listen for the `onKeyDown` event: app/entry.tsx TypeScript JavaScriptTypeScript 'use client' export function Entry() { const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { if ( (e.ctrlKey || e.metaKey) && (e.key === 'Enter' || e.key === 'NumpadEnter') ) { e.preventDefault() e.currentTarget.form?.requestSubmit() } } return ( <div> <textarea name="entry" rows={20} required onKeyDown={handleKeyDown} /> </div> ) } This will trigger the submission of the nearest `<form>` ancestor, which will invoke the Server Action. ### [Non-form Elements](#non-form-elements) While it's common to use Server Actions within `<form>` elements, they can also be invoked from other parts of your code such as event handlers and `useEffect`. #### [Event Handlers](#event-handlers) You can invoke a Server Action from event handlers such as `onClick`. For example, to increment a like count: app/like-button.tsx TypeScript JavaScriptTypeScript 'use client' import { incrementLike } from './actions' import { useState } from 'react' export default function LikeButton({ initialLikes }: { initialLikes: number }) { const [likes, setLikes] = useState(initialLikes) return ( <> <p>Total Likes: {likes}</p> <button onClick={async () => { const updatedLikes = await incrementLike() setLikes(updatedLikes) }} > Like </button> </> ) } To improve the user experience, we recommend using other React APIs like [`useOptimistic`](https://react.dev/reference/react/useOptimistic) and [`useTransition`](https://react.dev/reference/react/useTransition) to update the UI before the Server Action finishes executing on the server, or to show a pending state. You can also add event handlers to form elements, for example, to save a form field `onChange`: app/ui/edit-post.tsx 'use client' import { publishPost, saveDraft } from './actions' export default function EditPost() { return ( <form action={publishPost}> <textarea name="content" onChange={async (e) => { await saveDraft(e.target.value) }} /> <button type="submit">Publish</button> </form> ) } For cases like this, where multiple events might be fired in quick succession, we recommend **debouncing** to prevent unnecessary Server Action invocations. #### [`useEffect`](#useeffect) You can use the React [`useEffect`](https://react.dev/reference/react/useEffect) hook to invoke a Server Action when the component mounts or a dependency changes. This is useful for mutations that depend on global events or need to be triggered automatically. For example, `onKeyDown` for app shortcuts, an intersection observer hook for infinite scrolling, or when the component mounts to update a view count: app/view-count.tsx TypeScript JavaScriptTypeScript 'use client' import { incrementViews } from './actions' import { useState, useEffect } from 'react' export default function ViewCount({ initialViews }: { initialViews: number }) { const [views, setViews] = useState(initialViews) useEffect(() => { const updateViews = async () => { const updatedViews = await incrementViews() setViews(updatedViews) } updateViews() }, []) return <p>Total Views: {views}</p> } Remember to consider the [behavior and caveats](https://react.dev/reference/react/useEffect#caveats) of `useEffect`. ### [Error Handling](#error-handling) When an error is thrown, it'll be caught by the nearest [`error.js`](/docs/app/building-your-application/routing/error-handling) or `<Suspense>` boundary on the client. We recommend using `try/catch` to return errors to be handled by your UI. For example, your Server Action might handle errors from creating a new item by returning a message: app/actions.ts TypeScript JavaScriptTypeScript 'use server' export async function createTodo(prevState: any, formData: FormData) { try { // Mutate data } catch (e) { throw new Error('Failed to create task') } } > **Good to know:** > > * Aside from throwing the error, you can also return an object to be handled by `useFormState`. See [Server-side validation and error handling](#server-side-validation-and-error-handling). ### [Revalidating data](#revalidating-data) You can revalidate the [Next.js Cache](/docs/app/building-your-application/caching) inside your Server Actions with the [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) API: app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { revalidatePath } from 'next/cache' export async function createPost() { try { // ... } catch (error) { // ... } revalidatePath('/posts') } Or invalidate a specific data fetch with a cache tag using [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag): app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { revalidateTag } from 'next/cache' export async function createPost() { try { // ... } catch (error) { // ... } revalidateTag('posts') } ### [Redirecting](#redirecting) If you would like to redirect the user to a different route after the completion of a Server Action, you can use [`redirect`](/docs/app/api-reference/functions/redirect) API. `redirect` needs to be called outside of the `try/catch` block: app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { redirect } from 'next/navigation' import { revalidateTag } from 'next/cache' export async function createPost(id: string) { try { // ... } catch (error) { // ... } revalidateTag('posts') // Update cached posts redirect(`/post/${id}`) // Navigate to the new post page } ### [Cookies](#cookies) You can `get`, `set`, and `delete` cookies inside a Server Action using the [`cookies`](/docs/app/api-reference/functions/cookies) API: app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { cookies } from 'next/headers' export async function exampleAction() { // Get cookie const value = cookies().get('name')?.value // Set cookie cookies().set('name', 'Delba') // Delete cookie cookies().delete('name') } See [additional examples](/docs/app/api-reference/functions/cookies#deleting-cookies) for deleting cookies from Server Actions. [Security](#security) --------------------- ### [Authentication and authorization](#authentication-and-authorization) You should treat Server Actions as you would public-facing API endpoints, and ensure that the user is authorized to perform the action. For example: app/actions.ts 'use server' import { auth } from './lib' export function addItem() { const { user } = auth() if (!user) { throw new Error('You must be signed in to perform this action') } // ... } ### [Closures and encryption](#closures-and-encryption) Defining a Server Action inside a component creates a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) where the action has access to the outer function's scope. For example, the `publish` action has access to the `publishVersion` variable: app/page.tsx TypeScript JavaScriptTypeScript export default function Page() { const publishVersion = await getLatestVersion(); async function publish(formData: FormData) { "use server"; if (publishVersion !== await getLatestVersion()) { throw new Error('The version has changed since pressing publish'); } ... } return <button action={publish}>Publish</button>; } Closures are useful when you need to capture a _snapshot_ of data (e.g. `publishVersion`) at the time of rendering so that it can be used later when the action is invoked. However, for this to happen, the captured variables are sent to the client and back to the server when the action is invoked. To prevent sensitive data from being exposed to the client, Next.js automatically encrypts the closed-over variables. A new private key is generated for each action every time a Next.js application is built. This means actions can only be invoked for a specific build. > **Good to know:** We don't recommend relying on encryption alone to prevent sensitive values from being exposed on the client. Instead, you should use the [React taint APIs](/docs/app/building-your-application/data-fetching/patterns#preventing-sensitive-data-from-being-exposed-to-the-client) to proactively prevent specific data from being sent to the client. ### [Overwriting encryption keys (advanced)](#overwriting-encryption-keys-advanced) When self-hosting your Next.js application across multiple servers, each server instance may end up with a different encryption key, leading to potential inconsistencies. To mitigate this, you can overwrite the encryption key using the `process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` environment variable. Specifying this variable ensures that your encryption keys are persistent across builds, and all server instances use the same key. This is an advanced use case where consistent encryption behavior across multiple deployments is critical for your application. You should consider standard security practices such key rotation and signing. > **Good to know:** Next.js applications deployed to Vercel automatically handle this. ### [Allowed origins (advanced)](#allowed-origins-advanced) Since Server Actions can be invoked in a `<form>` element, this opens them up to [CSRF attacks](https://developer.mozilla.org/en-US/docs/Glossary/CSRF). Behind the scenes, Server Actions use the `POST` method, and only this HTTP method is allowed to invoke them. This prevents most CSRF vulnerabilities in modern browsers, particularly with [SameSite cookies](https://web.dev/articles/samesite-cookies-explained) being the default. As an additional protection, Server Actions in Next.js also compare the [Origin header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) to the [Host header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host) (or `X-Forwarded-Host`). If these don't match, the request will be aborted. In other words, Server Actions can only be invoked on the same host as the page that hosts it. For large applications that use reverse proxies or multi-layered backend architectures (where the server API differs from the production domain), it's recommended to use the configuration option [`serverActions.allowedOrigins`](/docs/app/api-reference/next-config-js/serverActions) option to specify a list of safe origins. The option accepts an array of strings. next.config.js /** @type {import('next').NextConfig} */ module.exports = { experimental: { serverActions: { allowedOrigins: ['my-proxy.com', '*.my-proxy.com'], }, }, } Learn more about [Security and Server Actions](https://nextjs.org/blog/security-nextjs-server-components-actions). [Additional resources](#additional-resources) --------------------------------------------- For more information on Server Actions, check out the following React docs: * [`"use server"`](https://react.dev/reference/react/use-server) * [`<form>`](https://react.dev/reference/react-dom/components/form) * [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus) * [`useFormState`](https://react.dev/reference/react-dom/hooks/useFormState) * [`useOptimistic`](https://react.dev/reference/react/useOptimistic) Next Steps ---------- Learn how to configure Server Actions in Next.js [ App Router ... next.config.js Options ### serverActions Configure Server Actions behavior in your Next.js application. ](/docs/app/api-reference/next-config-js/serverActions) [Previous Fetching, Caching, and Revalidating ](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) [Next Data Fetching Patterns and Best Practices ](/docs/app/building-your-application/data-fetching/patterns) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"35dc5532c9fa06308b8bd21f71040630\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/rendering
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Fundamentals](#fundamentals) * [Rendering Environments](#rendering-environments) * [Request-Response Lifecycle](#request-response-lifecycle) * [Network Boundary](#network-boundary) * [Building Hybrid Applications](#building-hybrid-applications) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/03-rendering/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Rendering Rendering ========= Rendering converts the code you write into user interfaces. React and Next.js allow you to create hybrid web applications where parts of your code can be rendered on the server or the client. This section will help you understand the differences between these rendering environments, strategies, and runtimes. [Fundamentals](#fundamentals) ----------------------------- To start, it's helpful to be familiar with three foundational web concepts: * The [Environments](#rendering-environments) your application code can be executed in: the server and the client. * The [Request-Response Lifecycle](#request-response-lifecycle) that's initiated when a user visits or interacts with your application. * The [Network Boundary](#network-boundary) that separates server and client code. ### [Rendering Environments](#rendering-environments) There are two environments where web applications can be rendered: the client and the server. ![Client and Server Environments](/_next/image?url=%2Fdocs%2Flight%2Fclient-and-server-environments.png&w=3840&q=75)![Client and Server Environments](/_next/image?url=%2Fdocs%2Fdark%2Fclient-and-server-environments.png&w=3840&q=75) * The **client** refers to the browser on a user's device that sends a request to a server for your application code. It then turns the response from the server into a user interface. * The **server** refers to the computer in a data center that stores your application code, receives requests from a client, and sends back an appropriate response. Historically, developers had to use different languages (e.g. JavaScript, PHP) and frameworks when writing code for the server and the client. With React, developers can use the **same language** (JavaScript), and the **same framework** (e.g. Next.js or your framework of choice). This flexibility allows you to seamlessly write code for both environments without context switching. However, each environment has its own set of capabilities and constraints. Therefore, the code you write for the server and the client is not always the same. There are certain operations (e.g. data fetching or managing user state) that are better suited for one environment over the other. Understanding these differences is key to effectively using React and Next.js. We'll cover the differences and use cases in more detail on the [Server](/docs/app/building-your-application/rendering/server-components) and [Client](/docs/app/building-your-application/rendering/client-components) Components pages, for now, let's continue building on our foundation. ### [Request-Response Lifecycle](#request-response-lifecycle) Broadly speaking, all websites follow the same **Request-Response Lifecycle**: 1. **User Action:** The user interacts with a web application. This could be clicking a link, submitting a form, or typing a URL directly into the browser's address bar. 2. **HTTP Request:** The client sends an [HTTP](https://developer.mozilla.org/docs/Web/HTTP) request to the server that contains necessary information about what resources are being requested, what method is being used (e.g. `GET`, `POST`), and additional data if necessary. 3. **Server:** The server processes the request and responds with the appropriate resources. This process may take a couple of steps like routing, fetching data, etc. 4. **HTTP Response:** After processing the request, the server sends an HTTP response back to the client. This response contains a status code (which tells the client whether the request was successful or not) and requested resources (e.g. HTML, CSS, JavaScript, static assets, etc). 5. **Client:** The client parses the resources to render the user interface. 6. **User Action:** Once the user interface is rendered, the user can interact with it, and the whole process starts again. A major part of building a hybrid web application is deciding how to split the work in the lifecycle, and where to place the Network Boundary. ### [Network Boundary](#network-boundary) In web development, the **Network Boundary** is a conceptual line that separates the different environments. For example, the client and the server, or the server and the data store. In React, you choose where to place the client-server network boundary wherever it makes the most sense. Behind the scenes, the work is split into two parts: the **client module graph** and the **server module graph**. The server module graph contains all the components that are rendered on the server, and the client module graph contains all components that are rendered on the client. It may be helpful to think about module graphs as a visual representation of how files in your application depend on each other. You can use the React `"use client"` convention to define the boundary. There's also a `"use server"` convention, which tells React to do some computational work on the server. [Building Hybrid Applications](#building-hybrid-applications) ------------------------------------------------------------- When working in these environments, it's helpful to think of the flow of the code in your application as **unidirectional**. In other words, during a response, your application code flows in one direction: from the server to the client. If you need to access the server from the client, you send a **new** request to the server rather than re-use the same request. This makes it easier to understand where to render your components and where to place the Network Boundary. In practice, this model encourages developers to think about what they want to execute on the server first, before sending the result to the client and making the application interactive. This concept will become clearer when we look at how you can [interleave client and server components](/docs/app/building-your-application/rendering/composition-patterns) in the same component tree. [ ### Server Components Learn how you can use React Server Components to render parts of your application on the server. ](/docs/app/building-your-application/rendering/server-components)[ ### Client Components Learn how to use Client Components to render parts of your application on the client. ](/docs/app/building-your-application/rendering/client-components)[ ### Composition Patterns Recommended patterns for using Server and Client Components. ](/docs/app/building-your-application/rendering/composition-patterns)[ ### Edge and Node.js Runtimes Learn about the switchable runtimes (Edge and Node.js) in Next.js. ](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) [Previous Data Fetching Patterns and Best Practices ](/docs/app/building-your-application/data-fetching/patterns) [Next Server Components ](/docs/app/building-your-application/rendering/server-components) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"bb89ba2a635a210f833e3c046eddfaf2\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/rendering/server-components
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [ Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Benefits of Server Rendering](#benefits-of-server-rendering) * [Using Server Components in Next.js](#using-server-components-in-nextjs) * [How are Server Components rendered?](#how-are-server-components-rendered) * [Server Rendering Strategies](#server-rendering-strategies) * [Static Rendering (Default)](#static-rendering-default) * [Dynamic Rendering](#dynamic-rendering) * [Switching to Dynamic Rendering](#switching-to-dynamic-rendering) * [Dynamic Functions](#dynamic-functions) * [Streaming](#streaming) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/03-rendering/01-server-components.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Rendering](/docs/app/building-your-application/rendering)Server Components Server Components ================= React Server Components allow you to write UI that can be rendered and optionally cached on the server. In Next.js, the rendering work is further split by route segments to enable streaming and partial rendering, and there are three different server rendering strategies: * [Static Rendering](#static-rendering-default) * [Dynamic Rendering](#dynamic-rendering) * [Streaming](#streaming) This page will go through how Server Components work, when you might use them, and the different server rendering strategies. [Benefits of Server Rendering](#benefits-of-server-rendering) ------------------------------------------------------------- There are a couple of benefits to doing the rendering work on the server, including: * **Data Fetching**: Server Components allow you to move data fetching to the server, closer to your data source. This can improve performance by reducing time it takes to fetch data needed for rendering, and the number of requests the client needs to make. * **Security**: Server Components allow you to keep sensitive data and logic on the server, such as tokens and API keys, without the risk of exposing them to the client. * **Caching**: By rendering on the server, the result can be cached and reused on subsequent requests and across users. This can improve performance and reduce cost by reducing the amount of rendering and data fetching done on each request. * **Performance**: Server Components give you additional tools to optimize performance from the baseline. For example, if you start with an app composed of entirely Client Components, moving non-interactive pieces of your UI to Server Components can reduce the amount of client-side JavaScript needed. This is beneficial for users with slower internet or less powerful devices, as the browser has less client-side JavaScript to download, parse, and execute. * **Initial Page Load and [First Contentful Paint (FCP)](https://web.dev/fcp/)**: On the server, we can generate HTML to allow users to view the page immediately, without waiting for the client to download, parse and execute the JavaScript needed to render the page. * **Search Engine Optimization and Social Network Shareability**: The rendered HTML can be used by search engine bots to index your pages and social network bots to generate social card previews for your pages. * **Streaming**: Server Components allow you to split the rendering work into chunks and stream them to the client as they become ready. This allows the user to see parts of the page earlier without having to wait for the entire page to be rendered on the server. [Using Server Components in Next.js](#using-server-components-in-nextjs) ------------------------------------------------------------------------ By default, Next.js uses Server Components. This allows you to automatically implement server rendering with no additional configuration, and you can opt into using Client Components when needed, see [Client Components](/docs/app/building-your-application/rendering/client-components). [How are Server Components rendered?](#how-are-server-components-rendered) -------------------------------------------------------------------------- On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks: by individual route segments and [Suspense Boundaries](https://react.dev/reference/react/Suspense). Each chunk is rendered in two steps: 1. React renders Server Components into a special data format called the **React Server Component Payload (RSC Payload)**. 2. Next.js uses the RSC Payload and Client Component JavaScript instructions to render **HTML** on the server. Then, on the client: 1. The HTML is used to immediately show a fast non-interactive preview of the route - this is for the initial page load only. 2. The React Server Components Payload is used to reconcile the Client and Server Component trees, and update the DOM. 3. The JavaScript instructions are used to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot) Client Components and make the application interactive. > **What is the React Server Component Payload (RSC)?** > > The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains: > > * The rendered result of Server Components > * Placeholders for where Client Components should be rendered and references to their JavaScript files > * Any props passed from a Server Component to a Client Component [Server Rendering Strategies](#server-rendering-strategies) ----------------------------------------------------------- There are three subsets of server rendering: Static, Dynamic, and Streaming. ### [Static Rendering (Default)](#static-rendering-default) With Static Rendering, routes are rendered at **build time**, or in the background after [data revalidation](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data). The result is cached and can be pushed to a [Content Delivery Network (CDN)](https://developer.mozilla.org/docs/Glossary/CDN). This optimization allows you to share the result of the rendering work between users and server requests. Static rendering is useful when a route has data that is not personalized to the user and can be known at build time, such as a static blog post or a product page. ### [Dynamic Rendering](#dynamic-rendering) With Dynamic Rendering, routes are rendered for each user at **request time**. Dynamic rendering is useful when a route has data that is personalized to the user or has information that can only be known at request time, such as cookies or the URL's search params. > **Dynamic Routes with Cached Data** > > In most websites, routes are not fully static or fully dynamic - it's a spectrum. For example, you can have an e-commerce page that uses cached product data that's revalidated at an interval, but also has uncached, personalized customer data. > > In Next.js, you can have dynamically rendered routes that have both cached and uncached data. This is because the RSC Payload and data are cached separately. This allows you to opt into dynamic rendering without worrying about the performance impact of fetching all the data at request time. > > Learn more about the [full-route cache](/docs/app/building-your-application/caching#full-route-cache) and [Data Cache](/docs/app/building-your-application/caching#data-cache). #### [Switching to Dynamic Rendering](#switching-to-dynamic-rendering) During rendering, if a [dynamic function](#dynamic-functions) or [uncached data request](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching) is discovered, Next.js will switch to dynamically rendering the whole route. This table summarizes how dynamic functions and data caching affect whether a route is statically or dynamically rendered: Dynamic Functions Data Route No Cached Statically Rendered Yes Cached Dynamically Rendered No Not Cached Dynamically Rendered Yes Not Cached Dynamically Rendered In the table above, for a route to be fully static, all data must be cached. However, you can have a dynamically rendered route that uses both cached and uncached data fetches. As a developer, you do not need to choose between static and dynamic rendering as Next.js will automatically choose the best rendering strategy for each route based on the features and APIs used. Instead, you choose when to [cache or revalidate specific data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating), and you may choose to [stream](#streaming) parts of your UI. #### [Dynamic Functions](#dynamic-functions) Dynamic functions rely on information that can only be known at request time such as a user's cookies, current requests headers, or the URL's search params. In Next.js, these dynamic functions are: * **[`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers)**: Using these in a Server Component will opt the whole route into dynamic rendering at request time. * **[`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)**: Using the `searchParams` prop on a [Page](/docs/app/api-reference/file-conventions/page) will opt the page into dynamic rendering at request time. Using any of these functions will opt the whole route into dynamic rendering at request time. ### [Streaming](#streaming) ![Diagram showing parallelization of route segments during streaming, showing data fetching, rendering, and hydration of individual chunks.](/_next/image?url=%2Fdocs%2Flight%2Fsequential-parallel-data-fetching.png&w=3840&q=75)![Diagram showing parallelization of route segments during streaming, showing data fetching, rendering, and hydration of individual chunks.](/_next/image?url=%2Fdocs%2Fdark%2Fsequential-parallel-data-fetching.png&w=3840&q=75) Streaming enables you to progressively render UI from the server. Work is split into chunks and streamed to the client as it becomes ready. This allows the user to see parts of the page immediately, before the entire content has finished rendering. ![Diagram showing partially rendered page on the client, with loading UI for chunks that are being streamed.](/_next/image?url=%2Fdocs%2Flight%2Fserver-rendering-with-streaming.png&w=3840&q=75)![Diagram showing partially rendered page on the client, with loading UI for chunks that are being streamed.](/_next/image?url=%2Fdocs%2Fdark%2Fserver-rendering-with-streaming.png&w=3840&q=75) Streaming is built into the Next.js App Router by default. This helps improve both the initial page loading performance, as well as UI that depends on slower data fetches that would block rendering the whole route. For example, reviews on a product page. You can start streaming route segments using `loading.js` and UI components with [React Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming). See the [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) section for more information. Next Steps ---------- Learn how Next.js caches data and the result of static rendering. [ App Router Building Your Application ### Caching An overview of caching mechanisms in Next.js. ](/docs/app/building-your-application/caching) [Previous Rendering ](/docs/app/building-your-application/rendering) [Next Client Components ](/docs/app/building-your-application/rendering/client-components) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"9f3003ae728d71a7a89fbdc42395889c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/getting-started
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [What is Next.js?](#what-is-nextjs) * [Main Features](#main-features) * [How to Use These Docs](#how-to-use-these-docs) * [App Router vs Pages Router](#app-router-vs-pages-router) * [Pre-Requisite Knowledge](#pre-requisite-knowledge) * [Accessibility](#accessibility) * [Join our Community](#join-our-community) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top Introduction ============ Welcome to the Next.js documentation! [What is Next.js?](#what-is-nextjs) ----------------------------------- 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. Under the hood, Next.js also abstracts and automatically configures tooling needed for React, like bundling, compiling, and more. This allows you to focus on building your application instead of spending time with configuration. Whether you're an individual developer or part of a larger team, Next.js can help you build interactive, dynamic, and fast React applications. [Main Features](#main-features) ------------------------------- Some of the main Next.js features include: Feature Description [Routing](/docs/app/building-your-application/routing) A file-system based router built on top of Server Components that supports layouts, nested routing, loading states, error handling, and more. [Rendering](/docs/app/building-your-application/rendering) Client-side and Server-side Rendering with Client and Server Components. Further optimized with Static and Dynamic Rendering on the server with Next.js. Streaming on Edge and Node.js runtimes. [Data Fetching](/docs/app/building-your-application/data-fetching) Simplified data fetching with async/await in Server Components, and an extended `fetch` API for request memoization, data caching and revalidation. [Styling](/docs/app/building-your-application/styling) Support for your preferred styling methods, including CSS Modules, Tailwind CSS, and CSS-in-JS [Optimizations](/docs/app/building-your-application/optimizing) Image, Fonts, and Script Optimizations to improve your application's Core Web Vitals and User Experience. [TypeScript](/docs/app/building-your-application/configuring/typescript) Improved support for TypeScript, with better type checking and more efficient compilation, as well as custom TypeScript Plugin and type checker. [How to Use These Docs](#how-to-use-these-docs) ----------------------------------------------- On the left side of the screen, you'll find the docs navbar. The pages of the docs are organized sequentially, from basic to advanced, so you can follow them step-by-step when building your application. However, you can read them in any order or skip to the pages that apply to your use case. On the right side of the screen, you'll see a table of contents that makes it easier to navigate between sections of a page. If you need to quickly find a page, you can use the search bar at the top, or the search shortcut (`Ctrl+K` or `Cmd+K`). To get started, checkout the [Installation](/docs/getting-started/installation) guide. [App Router vs Pages Router](#app-router-vs-pages-router) --------------------------------------------------------- Next.js has two different routers: the App Router and the Pages Router. The App Router is a newer router that allows you to use React's latest features, such as Server Components and Streaming. The Pages Router is the original Next.js router, which allowed you to build server-rendered React applications and continues to be supported for older Next.js applications. At the top of the sidebar, you'll notice a dropdown menu that allows you to switch between the **App Router** and the **Pages Router** features. Since there are features that are unique to each directory, it's important to keep track of which tab is selected. The breadcrumbs at the top of the page will also indicate whether you're viewing App Router docs or Pages Router docs. [Pre-Requisite Knowledge](#pre-requisite-knowledge) --------------------------------------------------- Although our docs are designed to be beginner-friendly, we need to establish a baseline so that the docs can stay focused on Next.js functionality. We'll make sure to provide links to relevant documentation whenever we introduce a new concept. To get the most out of our docs, it's recommended that you have a basic understanding of HTML, CSS, and React. If you need to brush up on your React skills, check out our [React Foundations Course](/learn/react-foundations), which will introduce you to the fundamentals. Then, learn more about Next.js by [building a dashboard application](/learn/dashboard-app). [Accessibility](#accessibility) ------------------------------- For optimal accessibility when using a screen reader while reading the docs, we recommend using Firefox and NVDA, or Safari and VoiceOver. [Join our Community](#join-our-community) ----------------------------------------- If you have questions about anything related to Next.js, you're always welcome to ask our community on [GitHub Discussions](https://github.com/vercel/next.js/discussions), [Discord](https://discord.com/invite/bUG2bvbtHy), [Twitter](https://twitter.com/nextjs), and [Reddit](https://www.reddit.com/r/nextjs). [ ### Getting Started Learn how to create full-stack web applications with Next.js. ](/docs/getting-started)[ ### App Router Use the new App Router with Next.js' and React's latest features, including Layouts, Server Components, Suspense, and more. ](/docs/app)[ ### Pages Router Before Next.js 13, the Pages Router was the main way to create routes in Next.js with an intuitive file-system router. ](/docs/pages)[ ### Architecture How Next.js Works ](/docs/architecture)[ ### Community Get involved in the Next.js community. ](/docs/community) [Next Installation ](/docs/getting-started/installation) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"99bf5f0248ddaa328b9e12eb7a949743\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/cookies
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [ cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [cookies().get(name)](#cookiesgetname) * [cookies().getAll()](#cookiesgetall) * [cookies().has(name)](#cookieshasname) * [cookies().set(name, value, options)](#cookiessetname-value-options) * [Deleting cookies](#deleting-cookies) * [cookies().delete(name)](#cookiesdeletename) * [cookies().set(name, '')](#cookiessetname-) * [cookies().set(name, value, { maxAge: 0 })](#cookiessetname-value--maxage-0-) * [cookies().set(name, value, { expires: timestamp })](#cookiessetname-value--expires-timestamp-) * [Version History](#version-history) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/cookies.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)cookies cookies ======= The `cookies` function allows you to read the HTTP incoming request cookies from a [Server Component](/docs/app/building-your-application/rendering/server-components) or write outgoing request cookies in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). > **Good to know**: `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering)** at request time. [`cookies().get(name)`](#cookiesgetname) ---------------------------------------- A method that takes a cookie name and returns an object with name and value. If a cookie with `name` isn't found, it returns `undefined`. If multiple cookies match, it will only return the first match. app/page.js import { cookies } from 'next/headers' export default function Page() { const cookieStore = cookies() const theme = cookieStore.get('theme') return '...' } [`cookies().getAll()`](#cookiesgetall) -------------------------------------- A method that is similar to `get`, but returns a list of all the cookies with a matching `name`. If `name` is unspecified, it returns all the available cookies. app/page.js import { cookies } from 'next/headers' export default function Page() { const cookieStore = cookies() return cookieStore.getAll().map((cookie) => ( <div key={cookie.name}> <p>Name: {cookie.name}</p> <p>Value: {cookie.value}</p> </div> )) } [`cookies().has(name)`](#cookieshasname) ---------------------------------------- A method that takes a cookie name and returns a `boolean` based on if the cookie exists (`true`) or not (`false`). app/page.js import { cookies } from 'next/headers' export default function Page() { const cookieStore = cookies() const hasCookie = cookieStore.has('theme') return '...' } [`cookies().set(name, value, options)`](#cookiessetname-value-options) ---------------------------------------------------------------------- A method that takes a cookie name, value, and options and sets the outgoing request cookie. > **Good to know**: HTTP does not allow setting cookies after streaming starts, so you must use `.set()` in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). app/actions.js 'use server' import { cookies } from 'next/headers' async function create(data) { cookies().set('name', 'lee') // or cookies().set('name', 'lee', { secure: true }) // or cookies().set({ name: 'name', value: 'lee', httpOnly: true, path: '/', }) } [Deleting cookies](#deleting-cookies) ------------------------------------- > **Good to know**: You can only delete cookies in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). There are several options for deleting a cookie: ### [`cookies().delete(name)`](#cookiesdeletename) You can explicitly delete a cookie with a given name. app/actions.js 'use server' import { cookies } from 'next/headers' async function delete(data) { cookies().delete('name') } ### [`cookies().set(name, '')`](#cookiessetname-) Alternatively, you can set a new cookie with the same name and an empty value. app/actions.js 'use server' import { cookies } from 'next/headers' async function delete(data) { cookies().set('name', '') } > **Good to know**: `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers). ### [`cookies().set(name, value, { maxAge: 0 })`](#cookiessetname-value--maxage-0-) Setting `maxAge` to 0 will immediately expire a cookie. app/actions.js 'use server' import { cookies } from 'next/headers' async function delete(data) { cookies().set('name', 'value', { maxAge: 0 }) } ### [`cookies().set(name, value, { expires: timestamp })`](#cookiessetname-value--expires-timestamp-) Setting `expires` to any value in the past will immediately expire a cookie. app/actions.js 'use server' import { cookies } from 'next/headers' async function delete(data) { const oneDay = 24 * 60 * 60 * 1000 cookies().set('name', 'value', { expires: Date.now() - oneDay }) } > **Good to know**: You can only delete cookies that belong to the same domain from which `.set()` is called. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete. [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `cookies` introduced. Next Steps ---------- For more information on what to do next, we recommend the following sections [ App Router ... Data Fetching ### Server Actions and Mutations Learn how to handle form submissions and data mutations with Next.js. ](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) [Previous Functions ](/docs/app/api-reference/functions) [Next draftMode ](/docs/app/api-reference/functions/draft-mode) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"f1391d688c57bd4ddea66e640334c86c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/getting-started/installation
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Automatic Installation](#automatic-installation) * [Manual Installation](#manual-installation) * [Creating directories](#creating-directories) * [The app directory](#the-app-directory) * [The pages directory (optional)](#the-pages-directory-optional) * [The public folder (optional)](#the-public-folder-optional) * [Run the Development Server](#run-the-development-server) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/01-getting-started/01-installation.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [Getting Started](/docs/getting-started)Installation Installation ============ System Requirements: * [Node.js 18.17](https://nodejs.org/) or later. * macOS, Windows (including WSL), and Linux are supported. [Automatic Installation](#automatic-installation) ------------------------------------------------- We recommend starting a new Next.js app using [`create-next-app`](/docs/app/api-reference/create-next-app), which sets up everything automatically for you. To create a project, run: Terminal npx create-next-app@latest On installation, you'll see the following prompts: Terminal What is your project named? my-app Would you like to use TypeScript? No / Yes Would you like to use ESLint? No / Yes Would you like to use Tailwind CSS? No / Yes Would you like to use `src/` directory? No / Yes Would you like to use App Router? (recommended) No / Yes Would you like to customize the default import alias (@/*)? No / Yes What import alias would you like configured? @/* After the prompts, `create-next-app` will create a folder with your project name and install the required dependencies. If you're new to Next.js, see the [project structure](/docs/getting-started/project-structure) docs for an overview of all the possible files and folders in your application. > **Good to know**: > > * Next.js now ships with [TypeScript](/docs/app/building-your-application/configuring/typescript), [ESLint](/docs/app/building-your-application/configuring/eslint), and [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) configuration by default. > * You can optionally use a [`src` directory](/docs/app/building-your-application/configuring/src-directory) in the root of your project to separate your application's code from configuration files. [Manual Installation](#manual-installation) ------------------------------------------- To manually create a new Next.js app, install the required packages: Terminal npm install next@latest react@latest react-dom@latest Open your `package.json` file and add the following `scripts`: package.json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" } } These scripts refer to the different stages of developing an application: * `dev`: runs [`next dev`](/docs/app/api-reference/next-cli#development) to start Next.js in development mode. * `build`: runs [`next build`](/docs/app/api-reference/next-cli#build) to build the application for production usage. * `start`: runs [`next start`](/docs/app/api-reference/next-cli#production) to start a Next.js production server. * `lint`: runs [`next lint`](/docs/app/api-reference/next-cli#lint) to set up Next.js' built-in ESLint configuration. ### [Creating directories](#creating-directories) Next.js uses file-system routing, which means the routes in your application are determined by how you structure your files. #### [The `app` directory](#the-app-directory) For new applications, we recommend using the [App Router](/docs/app). This router allows you to use React's latest features and is an evolution of the [Pages Router](/docs/pages) based on community feedback. Create an `app/` folder, then add a `layout.tsx` and `page.tsx` file. These will be rendered when the user visits the root of your application (`/`). ![App Folder Structure](/_next/image?url=%2Fdocs%2Flight%2Fapp-getting-started.png&w=3840&q=75)![App Folder Structure](/_next/image?url=%2Fdocs%2Fdark%2Fapp-getting-started.png&w=3840&q=75) Create a [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) inside `app/layout.tsx` with the required `<html>` and `<body>` tags: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> ) } Finally, create a home page `app/page.tsx` with some initial content: app/page.tsx TypeScript JavaScriptTypeScript export default function Page() { return <h1>Hello, Next.js!</h1> } > **Good to know**: If you forget to create `layout.tsx`, Next.js will automatically create this file when running the development server with `next dev`. Learn more about [using the App Router](/docs/app/building-your-application/routing/defining-routes). #### [The `pages` directory (optional)](#the-pages-directory-optional) If you prefer to use the Pages Router instead of the App Router, you can create a `pages/` directory at the root of your project. Then, add an `index.tsx` file inside your `pages` folder. This will be your home page (`/`): pages/index.tsx TypeScript JavaScriptTypeScript export default function Page() { return <h1>Hello, Next.js!</h1> } Next, add an `_app.tsx` file inside `pages/` to define the global layout. Learn more about the [custom App file](/docs/pages/building-your-application/routing/custom-app). pages/\_app.tsx TypeScript JavaScriptTypeScript import type { AppProps } from 'next/app' export default function App({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } Finally, add a `_document.tsx` file inside `pages/` to control the initial response from the server. Learn more about the [custom Document file](/docs/pages/building-your-application/routing/custom-document). pages/\_document.tsx TypeScript JavaScriptTypeScript import { Html, Head, Main, NextScript } from 'next/document' export default function Document() { return ( <Html> <Head /> <body> <Main /> <NextScript /> </body> </Html> ) } Learn more about [using the Pages Router](/docs/pages/building-your-application/routing/pages-and-layouts). > **Good to know**: Although you can use both routers in the same project, routes in `app` will be prioritized over `pages`. We recommend using only one router in your new project to avoid confusion. #### [The `public` folder (optional)](#the-public-folder-optional) Create a `public` folder to store static assets such as images, fonts, etc. Files inside `public` directory can then be referenced by your code starting from the base URL (`/`). [Run the Development Server](#run-the-development-server) --------------------------------------------------------- 1. Run `npm run dev` to start the development server. 2. Visit `http://localhost:3000` to view your application. 3. Edit `app/page.tsx` (or `pages/index.tsx`) file and save it to see the updated result in your browser. Next Steps ---------- Learn about the files and folders in your Next.js project. [ Getting Started ### Project Structure A list of folders and files conventions in a Next.js project ](/docs/getting-started/project-structure) [Previous Introduction ](/docs) [Next Project Structure ](/docs/getting-started/project-structure) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"eb6f40af3dfcab15488fec496a01b7a5\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/rendering/client-components
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [ Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Benefits of Client Rendering](#benefits-of-client-rendering) * [Using Client Components in Next.js](#using-client-components-in-nextjs) * [How are Client Components Rendered?](#how-are-client-components-rendered) * [Full page load](#full-page-load) * [Subsequent Navigations](#subsequent-navigations) * [Going back to the Server Environment](#going-back-to-the-server-environment) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Rendering](/docs/app/building-your-application/rendering)Client Components Client Components ================= Client Components allow you to write interactive UI that is [prerendered on the server](https://github.com/reactwg/server-components/discussions/4) and can use client JavaScript to run in the browser. This page will go through how Client Components work, how they're rendered, and when you might use them. [Benefits of Client Rendering](#benefits-of-client-rendering) ------------------------------------------------------------- There are a couple of benefits to doing the rendering work on the client, including: * **Interactivity**: Client Components can use state, effects, and event listeners, meaning they can provide immediate feedback to the user and update the UI. * **Browser APIs**: Client Components have access to browser APIs, like [geolocation](https://developer.mozilla.org/docs/Web/API/Geolocation_API) or [localStorage](https://developer.mozilla.org/docs/Web/API/Window/localStorage). [Using Client Components in Next.js](#using-client-components-in-nextjs) ------------------------------------------------------------------------ To use Client Components, you can add the React [`"use client"` directive](https://react.dev/reference/react/use-client) at the top of a file, above your imports. `"use client"` is used to declare a [boundary](/docs/app/building-your-application/rendering#network-boundary) between a Server and Client Component modules. This means that by defining a `"use client"` in a file, all other modules imported into it, including child components, are considered part of the client bundle. app/counter.tsx TypeScript JavaScriptTypeScript 'use client' import { useState } from 'react' export default function Counter() { const [count, setCount] = useState(0) return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ) } The diagram below shows that using `onClick` and `useState` in a nested component (`toggle.js`) will cause an error if the `"use client"` directive is not defined. This is because, by default, all components in the App Router are Server Components where these APIs are not available. By defining the `"use client"` directive in `toggle.js`, you can tell React to enter the client boundary where these APIs are available. ![Use Client Directive and Network Boundary](/_next/image?url=%2Fdocs%2Flight%2Fuse-client-directive.png&w=3840&q=75)![Use Client Directive and Network Boundary](/_next/image?url=%2Fdocs%2Fdark%2Fuse-client-directive.png&w=3840&q=75) > **Defining multiple `use client` entry points**: > > You can define multiple "use client" entry points in your React Component tree. This allows you to split your application into multiple client bundles. > > However, `"use client"` doesn't need to be defined in every component that needs to be rendered on the client. Once you define the boundary, all child components and modules imported into it are considered part of the client bundle. [How are Client Components Rendered?](#how-are-client-components-rendered) -------------------------------------------------------------------------- In Next.js, Client Components are rendered differently depending on whether the request is part of a full page load (an initial visit to your application or a page reload triggered by a browser refresh) or a subsequent navigation. ### [Full page load](#full-page-load) To optimize the initial page load, Next.js will use React's APIs to render a static HTML preview on the server for both Client and Server Components. This means, when the user first visits your application, they will see the content of the page immediately, without having to wait for the client to download, parse, and execute the Client Component JavaScript bundle. On the server: 1. React renders Server Components into a special data format called the **React Server Component Payload (RSC Payload)**, which includes references to Client Components. 2. Next.js uses the RSC Payload and Client Component JavaScript instructions to render **HTML** for the route on the server. Then, on the client: 1. The HTML is used to immediately show a fast non-interactive initial preview of the route. 2. The React Server Components Payload is used to reconcile the Client and Server Component trees, and update the DOM. 3. The JavaScript instructions are used to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot) Client Components and make their UI interactive. > **What is hydration?** > > Hydration is the process of attaching event listeners to the DOM, to make the static HTML interactive. Behind the scenes, hydration is done with the [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) React API. ### [Subsequent Navigations](#subsequent-navigations) On subsequent navigations, Client Components are rendered entirely on the client, without the server-rendered HTML. This means the Client Component JavaScript bundle is downloaded and parsed. Once the bundle is ready, React will use the RSC Payload to reconcile the Client and Server Component trees, and update the DOM. [Going back to the Server Environment](#going-back-to-the-server-environment) ----------------------------------------------------------------------------- Sometimes, after you've declared the `"use client"` boundary, you may want to go back to the server environment. For example, you may want to reduce the client bundle size, fetch data on the server, or use an API that is only available on the server. You can keep code on the server even though it's theoretically nested inside Client Components by interleaving Client and Server Components and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). See the [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) page for more information. [Previous Server Components ](/docs/app/building-your-application/rendering/server-components) [Next Composition Patterns ](/docs/app/building-your-application/rendering/composition-patterns) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"2cb1f0fa3646079e918860c392c55643\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)Building Your Application Building Your Application ========================= Next.js provides the building blocks to create flexible, full-stack web applications. The guides in **Building Your Application** explain how to use these features and how to customize your application's behavior. The sections and pages are organized sequentially, from basic to advanced, so you can follow them step-by-step when building your Next.js application. However, you can read them in any order or skip to the pages that apply to your use case. If you're new to Next.js, we recommend starting with the [Routing](/docs/app/building-your-application/routing), [Rendering](/docs/app/building-your-application/rendering), [Data Fetching](/docs/app/building-your-application/data-fetching) and [Styling](/docs/app/building-your-application/styling) sections, as they introduce the fundamental Next.js and web concepts to help you get started. Then, you can dive deeper into the other sections such as [Optimizing](/docs/app/building-your-application/optimizing) and [Configuring](/docs/app/building-your-application/configuring). Finally, once you're ready, checkout the [Deploying](/docs/app/building-your-application/deploying) and [Upgrading](/docs/app/building-your-application/upgrading) sections. [ ### Routing Learn the fundamentals of routing for front-end applications. ](/docs/app/building-your-application/routing)[ ### Data Fetching Learn how to fetch, cache, revalidate, and mutate data with Next.js. ](/docs/app/building-your-application/data-fetching)[ ### Rendering Learn the differences between Next.js rendering environments, strategies, and runtimes. ](/docs/app/building-your-application/rendering)[ ### Caching An overview of caching mechanisms in Next.js. ](/docs/app/building-your-application/caching)[ ### Styling Learn the different ways you can style your Next.js application. ](/docs/app/building-your-application/styling)[ ### Optimizing Optimize your Next.js application for best performance and user experience. ](/docs/app/building-your-application/optimizing)[ ### Configuring Learn how to configure your Next.js application. ](/docs/app/building-your-application/configuring)[ ### Testing Learn how to set up Next.js with four commonly used testing tools — Cypress, Playwright, Vitest, and Jest. ](/docs/app/building-your-application/testing)[ ### Authentication Learn how to implement authentication in Next.js, covering best practices, securing routes, authorization techniques, and session management. ](/docs/app/building-your-application/authentication)[ ### Deploying Learn how to deploy your Next.js app to production, either managed or self-hosted. ](/docs/app/building-your-application/deploying)[ ### Upgrading Learn how to upgrade to the latest versions of Next.js. ](/docs/app/building-your-application/upgrading) [Previous App Router ](/docs/app) [Next Routing ](/docs/app/building-your-application/routing) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"c53c1ab0f2253ff3205e36bee8bfe982\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/caching
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Overview](#overview) * [Request Memoization](#request-memoization) * [Duration](#duration) * [Revalidating](#revalidating) * [Opting out](#opting-out) * [Data Cache](#data-cache) * [Duration](#duration-1) * [Revalidating](#revalidating-1) * [Time-based Revalidation](#time-based-revalidation) * [On-demand Revalidation](#on-demand-revalidation) * [Opting out](#opting-out-1) * [Full Route Cache](#full-route-cache) * [1\. React Rendering on the Server](#1-react-rendering-on-the-server) * [2\. Next.js Caching on the Server (Full Route Cache)](#2-nextjs-caching-on-the-server-full-route-cache) * [3\. React Hydration and Reconciliation on the Client](#3-react-hydration-and-reconciliation-on-the-client) * [4\. Next.js Caching on the Client (Router Cache)](#4-nextjs-caching-on-the-client-router-cache) * [5\. Subsequent Navigations](#5-subsequent-navigations) * [Static and Dynamic Rendering](#static-and-dynamic-rendering) * [Duration](#duration-2) * [Invalidation](#invalidation) * [Opting out](#opting-out-2) * [Router Cache](#router-cache) * [Duration](#duration-3) * [Invalidation](#invalidation-1) * [Opting out](#opting-out-3) * [Cache Interactions](#cache-interactions) * [Data Cache and Full Route Cache](#data-cache-and-full-route-cache) * [Data Cache and Client-side Router cache](#data-cache-and-client-side-router-cache) * [APIs](#apis) * [<Link>](#link) * [router.prefetch](#routerprefetch) * [router.refresh](#routerrefresh) * [fetch](#fetch) * [fetch options.cache](#fetch-optionscache) * [fetch options.next.revalidate](#fetch-optionsnextrevalidate) * [fetch options.next.tags and revalidateTag](#fetch-optionsnexttags-and-revalidatetag) * [revalidatePath](#revalidatepath) * [Dynamic Functions](#dynamic-functions) * [cookies](#cookies) * [Segment Config Options](#segment-config-options) * [generateStaticParams](#generatestaticparams) * [React cache function](#react-cache-function) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/04-caching/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Caching Caching in Next.js ================== Next.js improves your application's performance and reduces costs by caching rendering work and data requests. This page provides an in-depth look at Next.js caching mechanisms, the APIs you can use to configure them, and how they interact with each other. > **Good to know**: This page helps you understand how Next.js works under the hood but is **not** essential knowledge to be productive with Next.js. Most of Next.js' caching heuristics are determined by your API usage and have defaults for the best performance with zero or minimal configuration. [Overview](#overview) --------------------- Here's a high-level overview of the different caching mechanisms and their purpose: Mechanism What Where Purpose Duration [Request Memoization](#request-memoization) Return values of functions Server Re-use data in a React Component tree Per-request lifecycle [Data Cache](#data-cache) Data Server Store data across user requests and deployments Persistent (can be revalidated) [Full Route Cache](#full-route-cache) HTML and RSC payload Server Reduce rendering cost and improve performance Persistent (can be revalidated) [Router Cache](#router-cache) RSC Payload Client Reduce server requests on navigation User session or time-based By default, Next.js will cache as much as possible to improve performance and reduce cost. This means routes are **statically rendered** and data requests are **cached** unless you opt out. The diagram below shows the default caching behavior: when a route is statically rendered at build time and when a static route is first visited. ![Diagram showing the default caching behavior in Next.js for the four mechanisms, with HIT, MISS and SET at build time and when a route is first visited.](/_next/image?url=%2Fdocs%2Flight%2Fcaching-overview.png&w=3840&q=75)![Diagram showing the default caching behavior in Next.js for the four mechanisms, with HIT, MISS and SET at build time and when a route is first visited.](/_next/image?url=%2Fdocs%2Fdark%2Fcaching-overview.png&w=3840&q=75) Caching behavior changes depending on whether the route is statically or dynamically rendered, data is cached or uncached, and whether a request is part of an initial visit or a subsequent navigation. Depending on your use case, you can configure the caching behavior for individual routes and data requests. [Request Memoization](#request-memoization) ------------------------------------------- React extends the [`fetch` API](#fetch) to automatically **memoize** requests that have the same URL and options. This means you can call a fetch function for the same data in multiple places in a React component tree while only executing it once. ![Deduplicated Fetch Requests](/_next/image?url=%2Fdocs%2Flight%2Fdeduplicated-fetch-requests.png&w=3840&q=75)![Deduplicated Fetch Requests](/_next/image?url=%2Fdocs%2Fdark%2Fdeduplicated-fetch-requests.png&w=3840&q=75) For example, if you need to use the same data across a route (e.g. in a Layout, Page, and multiple components), you do not have to fetch data at the top of the tree, and forward props between components. Instead, you can fetch data in the components that need it without worrying about the performance implications of making multiple requests across the network for the same data. app/example.tsx TypeScript JavaScriptTypeScript async function getItem() { // The `fetch` function is automatically memoized and the result // is cached const res = await fetch('https://.../item/1') return res.json() } // This function is called twice, but only executed the first time const item = await getItem() // cache MISS // The second call could be anywhere in your route const item = await getItem() // cache HIT **How Request Memoization Works** ![Diagram showing how fetch memoization works during React rendering.](/_next/image?url=%2Fdocs%2Flight%2Frequest-memoization.png&w=3840&q=75)![Diagram showing how fetch memoization works during React rendering.](/_next/image?url=%2Fdocs%2Fdark%2Frequest-memoization.png&w=3840&q=75) * While rendering a route, the first time a particular request is called, its result will not be in memory and it'll be a cache `MISS`. * Therefore, the function will be executed, and the data will be fetched from the external source, and the result will be stored in memory. * Subsequent function calls of the request in the same render pass will be a cache `HIT`, and the data will be returned from memory without executing the function. * Once the route has been rendered and the rendering pass is complete, memory is "reset" and all request memoization entries are cleared. > **Good to know**: > > * Request memoization is a React feature, not a Next.js feature. It's included here to show how it interacts with the other caching mechanisms. > * Memoization only applies to the `GET` method in `fetch` requests. > * Memoization only applies to the React Component tree, this means: > * It applies to `fetch` requests in `generateMetadata`, `generateStaticParams`, Layouts, Pages, and other Server Components. > * It doesn't apply to `fetch` requests in Route Handlers as they are not a part of the React component tree. > * For cases where `fetch` is not suitable (e.g. some database clients, CMS clients, or GraphQL clients), you can use the [React `cache` function](#react-cache-function) to memoize functions. ### [Duration](#duration) The cache lasts the lifetime of a server request until the React component tree has finished rendering. ### [Revalidating](#revalidating) Since the memoization is not shared across server requests and only applies during rendering, there is no need to revalidate it. ### [Opting out](#opting-out) Memoization only applies to the `GET` method in `fetch` requests, other methods, such as `POST` and `DELETE`, are not memoized. This default behavior is a React optimization and we do not recommend opting out of it. To manage individual requests, you can use the [`signal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/signal) property from [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). However, this will not opt requests out of memoization, rather, abort in-flight requests. app/example.js const { signal } = new AbortController() fetch(url, { signal }) [Data Cache](#data-cache) ------------------------- Next.js has a built-in Data Cache that **persists** the result of data fetches across incoming **server requests** and **deployments**. This is possible because Next.js extends the native `fetch` API to allow each request on the server to set its own persistent caching semantics. > **Good to know**: In the browser, the `cache` option of `fetch` indicates how a request will interact with the browser's HTTP cache, in Next.js, the `cache` option indicates how a server-side request will interact with the server's Data Cache. By default, data requests that use `fetch` are **cached**. You can use the [`cache`](#fetch-optionscache) and [`next.revalidate`](#fetch-optionsnextrevalidate) options of `fetch` to configure the caching behavior. **How the Data Cache Works** ![Diagram showing how cached and uncached fetch requests interact with the Data Cache. Cached requests are stored in the Data Cache, and memoized, uncached requests are fetched from the data source, not stored in the Data Cache, and memoized.](/_next/image?url=%2Fdocs%2Flight%2Fdata-cache.png&w=3840&q=75)![Diagram showing how cached and uncached fetch requests interact with the Data Cache. Cached requests are stored in the Data Cache, and memoized, uncached requests are fetched from the data source, not stored in the Data Cache, and memoized.](/_next/image?url=%2Fdocs%2Fdark%2Fdata-cache.png&w=3840&q=75) * The first time a `fetch` request is called during rendering, Next.js checks the Data Cache for a cached response. * If a cached response is found, it's returned immediately and [memoized](#request-memoization). * If a cached response is not found, the request is made to the data source, the result is stored in the Data Cache, and memoized. * For uncached data (e.g. `{ cache: 'no-store' }`), the result is always fetched from the data source, and memoized. * Whether the data is cached or uncached, the requests are always memoized to avoid making duplicate requests for the same data during a React render pass. > **Differences between the Data Cache and Request Memoization** > > While both caching mechanisms help improve performance by re-using cached data, the Data Cache is persistent across incoming requests and deployments, whereas memoization only lasts the lifetime of a request. > > With memoization, we reduce the number of **duplicate** requests in the same render pass that have to cross the network boundary from the rendering server to the Data Cache server (e.g. a CDN or Edge Network) or data source (e.g. a database or CMS). With the Data Cache, we reduce the number of requests made to our origin data source. ### [Duration](#duration-1) The Data Cache is persistent across incoming requests and deployments unless you revalidate or opt-out. ### [Revalidating](#revalidating-1) Cached data can be revalidated in two ways, with: * **Time-based Revalidation**: Revalidate data after a certain amount of time has passed and a new request is made. This is useful for data that changes infrequently and freshness is not as critical. * **On-demand Revalidation:** Revalidate data based on an event (e.g. form submission). On-demand revalidation can use a tag-based or path-based approach to revalidate groups of data at once. This is useful when you want to ensure the latest data is shown as soon as possible (e.g. when content from your headless CMS is updated). #### [Time-based Revalidation](#time-based-revalidation) To revalidate data at a timed interval, you can use the `next.revalidate` option of `fetch` to set the cache lifetime of a resource (in seconds). // Revalidate at most every hour fetch('https://...', { next: { revalidate: 3600 } }) Alternatively, you can use [Route Segment Config options](#segment-config-options) to configure all `fetch` requests in a segment or for cases where you're not able to use `fetch`. **How Time-based Revalidation Works** ![Diagram showing how time-based revalidation works, after the revalidation period, stale data is returned for the first request, then data is revalidated.](/_next/image?url=%2Fdocs%2Flight%2Ftime-based-revalidation.png&w=3840&q=75)![Diagram showing how time-based revalidation works, after the revalidation period, stale data is returned for the first request, then data is revalidated.](/_next/image?url=%2Fdocs%2Fdark%2Ftime-based-revalidation.png&w=3840&q=75) * The first time a fetch request with `revalidate` is called, the data will be fetched from the external data source and stored in the Data Cache. * Any requests that are called within the specified timeframe (e.g. 60-seconds) will return the cached data. * After the timeframe, the next request will still return the cached (now stale) data. * Next.js will trigger a revalidation of the data in the background. * Once the data is fetched successfully, Next.js will update the Data Cache with the fresh data. * If the background revalidation fails, the previous data will be kept unaltered. This is similar to [**stale-while-revalidate**](https://web.dev/stale-while-revalidate/) behavior. #### [On-demand Revalidation](#on-demand-revalidation) Data can be revalidated on-demand by path ([`revalidatePath`](#revalidatepath)) or by cache tag ([`revalidateTag`](#fetch-optionsnexttags-and-revalidatetag)). **How On-Demand Revalidation Works** ![Diagram showing how on-demand revalidation works, the Data Cache is updated with fresh data after a revalidation request.](/_next/image?url=%2Fdocs%2Flight%2Fon-demand-revalidation.png&w=3840&q=75)![Diagram showing how on-demand revalidation works, the Data Cache is updated with fresh data after a revalidation request.](/_next/image?url=%2Fdocs%2Fdark%2Fon-demand-revalidation.png&w=3840&q=75) * The first time a `fetch` request is called, the data will be fetched from the external data source and stored in the Data Cache. * When an on-demand revalidation is triggered, the appropriate cache entries will be purged from the cache. * This is different from time-based revalidation, which keeps the stale data in the cache until the fresh data is fetched. * The next time a request is made, it will be a cache `MISS` again, and the data will be fetched from the external data source and stored in the Data Cache. ### [Opting out](#opting-out-1) For individual data fetches, you can opt out of caching by setting the [`cache`](#fetch-optionscache) option to `no-store`. This means data will be fetched whenever `fetch` is called. // Opt out of caching for an individual `fetch` request fetch(`https://...`, { cache: 'no-store' }) Alternatively, you can also use the [Route Segment Config options](#segment-config-options) to opt out of caching for a specific route segment. This will affect all data requests in the route segment, including third-party libraries. // Opt out of caching for all data requests in the route segment export const dynamic = 'force-dynamic' > **Note**: Data Cache is currently only available in pages/routes, not middleware. Any fetches done inside of your middleware will be uncached by default. > **Vercel Data Cache** > > If your Next.js application is deployed to Vercel, we recommend reading the [Vercel Data Cache](https://vercel.com/docs/infrastructure/data-cache) documentation for a better understanding of Vercel specific features. [Full Route Cache](#full-route-cache) ------------------------------------- > **Related terms**: > > You may see the terms **Automatic Static Optimization**, **Static Site Generation**, or **Static Rendering** being used interchangeably to refer to the process of rendering and caching routes of your application at build time. Next.js automatically renders and caches routes at build time. This is an optimization that allows you to serve the cached route instead of rendering on the server for every request, resulting in faster page loads. To understand how the Full Route Cache works, it's helpful to look at how React handles rendering, and how Next.js caches the result: ### [1\. React Rendering on the Server](#1-react-rendering-on-the-server) On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks: by individual routes segments and Suspense boundaries. Each chunk is rendered in two steps: 1. React renders Server Components into a special data format, optimized for streaming, called the **React Server Component Payload**. 2. Next.js uses the React Server Component Payload and Client Component JavaScript instructions to render **HTML** on the server. This means we don't have to wait for everything to render before caching the work or sending a response. Instead, we can stream a response as work is completed. > **What is the React Server Component Payload?** > > The React Server Component Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The React Server Component Payload contains: > > * The rendered result of Server Components > * Placeholders for where Client Components should be rendered and references to their JavaScript files > * Any props passed from a Server Component to a Client Component > > To learn more, see the [Server Components](/docs/app/building-your-application/rendering/server-components) documentation. ### [2\. Next.js Caching on the Server (Full Route Cache)](#2-nextjs-caching-on-the-server-full-route-cache) ![Default behavior of the Full Route Cache, showing how the React Server Component Payload and HTML are cached on the server for statically rendered routes.](/_next/image?url=%2Fdocs%2Flight%2Ffull-route-cache.png&w=3840&q=75)![Default behavior of the Full Route Cache, showing how the React Server Component Payload and HTML are cached on the server for statically rendered routes.](/_next/image?url=%2Fdocs%2Fdark%2Ffull-route-cache.png&w=3840&q=75) The default behavior of Next.js is to cache the rendered result (React Server Component Payload and HTML) of a route on the server. This applies to statically rendered routes at build time, or during revalidation. ### [3\. React Hydration and Reconciliation on the Client](#3-react-hydration-and-reconciliation-on-the-client) At request time, on the client: 1. The HTML is used to immediately show a fast non-interactive initial preview of the Client and Server Components. 2. The React Server Components Payload is used to reconcile the Client and rendered Server Component trees, and update the DOM. 3. The JavaScript instructions are used to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot) Client Components and make the application interactive. ### [4\. Next.js Caching on the Client (Router Cache)](#4-nextjs-caching-on-the-client-router-cache) The React Server Component Payload is stored in the client-side [Router Cache](#router-cache) - a separate in-memory cache, split by individual route segment. This Router Cache is used to improve the navigation experience by storing previously visited routes and prefetching future routes. ### [5\. Subsequent Navigations](#5-subsequent-navigations) On subsequent navigations or during prefetching, Next.js will check if the React Server Components Payload is stored in the Router Cache. If so, it will skip sending a new request to the server. If the route segments are not in the cache, Next.js will fetch the React Server Components Payload from the server, and populate the Router Cache on the client. ### [Static and Dynamic Rendering](#static-and-dynamic-rendering) Whether a route is cached or not at build time depends on whether it's statically or dynamically rendered. Static routes are cached by default, whereas dynamic routes are rendered at request time, and not cached. This diagram shows the difference between statically and dynamically rendered routes, with cached and uncached data: ![How static and dynamic rendering affects the Full Route Cache. Static routes are cached at build time or after data revalidation, whereas dynamic routes are never cached](/_next/image?url=%2Fdocs%2Flight%2Fstatic-and-dynamic-routes.png&w=3840&q=75)![How static and dynamic rendering affects the Full Route Cache. Static routes are cached at build time or after data revalidation, whereas dynamic routes are never cached](/_next/image?url=%2Fdocs%2Fdark%2Fstatic-and-dynamic-routes.png&w=3840&q=75) Learn more about [static and dynamic rendering](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies). ### [Duration](#duration-2) By default, the Full Route Cache is persistent. This means that the render output is cached across user requests. ### [Invalidation](#invalidation) There are two ways you can invalidate the Full Route Cache: * **[Revalidating Data](/docs/app/building-your-application/caching#revalidating)**: Revalidating the [Data Cache](#data-cache), will in turn invalidate the Router Cache by re-rendering components on the server and caching the new render output. * **Redeploying**: Unlike the Data Cache, which persists across deployments, the Full Route Cache is cleared on new deployments. ### [Opting out](#opting-out-2) You can opt out of the Full Route Cache, or in other words, dynamically render components for every incoming request, by: * **Using a [Dynamic Function](#dynamic-functions)**: This will opt the route out from the Full Route Cache and dynamically render it at request time. The Data Cache can still be used. * **Using the `dynamic = 'force-dynamic'` or `revalidate = 0` route segment config options**: This will skip the Full Route Cache and the Data Cache. Meaning components will be rendered and data fetched on every incoming request to the server. The Router Cache will still apply as it's a client-side cache. * **Opting out of the [Data Cache](#data-cache)**: If a route has a `fetch` request that is not cached, this will opt the route out of the Full Route Cache. The data for the specific `fetch` request will be fetched for every incoming request. Other `fetch` requests that do not opt out of caching will still be cached in the Data Cache. This allows for a hybrid of cached and uncached data. [Router Cache](#router-cache) ----------------------------- > **Related Terms:** > > You may see the Router Cache being referred to as **Client-side Cache** or **Prefetch Cache**. While **Prefetch Cache** refers to the prefetched route segments, **Client-side Cache** refers to the whole Router cache, which includes both visited and prefetched segments. This cache specifically applies to Next.js and Server Components, and is different to the browser's [bfcache](https://web.dev/bfcache/), though it has a similar result. Next.js has an in-memory client-side cache that stores the React Server Component Payload, split by individual route segments, for the duration of a user session. This is called the Router Cache. **How the Router Cache Works** ![How the Router cache works for static and dynamic routes, showing MISS and HIT for initial and subsequent navigations.](/_next/image?url=%2Fdocs%2Flight%2Frouter-cache.png&w=3840&q=75)![How the Router cache works for static and dynamic routes, showing MISS and HIT for initial and subsequent navigations.](/_next/image?url=%2Fdocs%2Fdark%2Frouter-cache.png&w=3840&q=75) As a user navigates between routes, Next.js caches visited route segments and [prefetches](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) the routes the user is likely to navigate to (based on `<Link>` components in their viewport). This results in an improved navigation experience for the user: * Instant backward/forward navigation because visited routes are cached and fast navigation to new routes because of prefetching and [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering). * No full-page reload between navigations, and React state and browser state are preserved. > **Difference between the Router Cache and Full Route Cache**: > > The Router Cache temporarily stores the React Server Component Payload in the browser for the duration of a user session, whereas the Full Route Cache persistently stores the React Server Component Payload and HTML on the server across multiple user requests. > > While the Full Route Cache only caches statically rendered routes, the Router Cache applies to both statically and dynamically rendered routes. ### [Duration](#duration-3) The cache is stored in the browser's temporary memory. Two factors determine how long the router cache lasts: * **Session**: The cache persists across navigation. However, it's cleared on page refresh. * **Automatic Invalidation Period**: The cache of an individual segment is automatically invalidated after a specific time. The duration depends on how the resource was [prefetched](/docs/app/api-reference/components/link#prefetch): * **Default Prefetching** (`prefetch={null}` or unspecified): 30 seconds * **Full Prefetching**: (`prefetch={true}` or `router.prefetch`): 5 minutes While a page refresh will clear **all** cached segments, the automatic invalidation period only affects the individual segment from the time it was prefetched. > **Note**: There is [experimental support](/docs/app/api-reference/next-config-js/staleTimes) for configuring these values as of v14.2.0-canary.53. ### [Invalidation](#invalidation-1) There are two ways you can invalidate the Router Cache: * In a **Server Action**: * Revalidating data on-demand by path with ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag with ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)) * Using [`cookies.set`](/docs/app/api-reference/functions/cookies#cookiessetname-value-options) or [`cookies.delete`](/docs/app/api-reference/functions/cookies#deleting-cookies) invalidates the Router Cache to prevent routes that use cookies from becoming stale (e.g. authentication). * Calling [`router.refresh`](/docs/app/api-reference/functions/use-router) will invalidate the Router Cache and make a new request to the server for the current route. ### [Opting out](#opting-out-3) It's not possible to opt out of the Router Cache. However, you can invalidate it by calling [`router.refresh`](/docs/app/api-reference/functions/use-router), [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath), or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) (see above). This will clear the cache and make a new request to the server, ensuring the latest data is shown. You can also opt out of **prefetching** by setting the `prefetch` prop of the `<Link>` component to `false`. However, this will still temporarily store the route segments for 30s to allow instant navigation between nested segments, such as tab bars, or back and forward navigation. Visited routes will still be cached. [Cache Interactions](#cache-interactions) ----------------------------------------- When configuring the different caching mechanisms, it's important to understand how they interact with each other: ### [Data Cache and Full Route Cache](#data-cache-and-full-route-cache) * Revalidating or opting out of the Data Cache **will** invalidate the Full Route Cache, as the render output depends on data. * Invalidating or opting out of the Full Route Cache **does not** affect the Data Cache. You can dynamically render a route that has both cached and uncached data. This is useful when most of your page uses cached data, but you have a few components that rely on data that needs to be fetched at request time. You can dynamically render without worrying about the performance impact of re-fetching all the data. ### [Data Cache and Client-side Router cache](#data-cache-and-client-side-router-cache) * Revalidating the Data Cache in a [Route Handler](/docs/app/building-your-application/routing/route-handlers) **will not** immediately invalidate the Router Cache as the Route Handler isn't tied to a specific route. This means Router Cache will continue to serve the previous payload until a hard refresh, or the automatic invalidation period has elapsed. * To immediately invalidate the Data Cache and Router cache, you can use [`revalidatePath`](#revalidatepath) or [`revalidateTag`](#fetch-optionsnexttags-and-revalidatetag) in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). [APIs](#apis) ------------- The following table provides an overview of how different Next.js APIs affect caching: API Router Cache Full Route Cache Data Cache React Cache [`<Link prefetch>`](#link) Cache [`router.prefetch`](#routerprefetch) Cache [`router.refresh`](#routerrefresh) Revalidate [`fetch`](#fetch) Cache Cache [`fetch` `options.cache`](#fetch-optionscache) Cache or Opt out [`fetch` `options.next.revalidate`](#fetch-optionsnextrevalidate) Revalidate Revalidate [`fetch` `options.next.tags`](#fetch-optionsnexttags-and-revalidatetag) Cache Cache [`revalidateTag`](#fetch-optionsnexttags-and-revalidatetag) Revalidate (Server Action) Revalidate Revalidate [`revalidatePath`](#revalidatepath) Revalidate (Server Action) Revalidate Revalidate [`const revalidate`](#segment-config-options) Revalidate or Opt out Revalidate or Opt out [`const dynamic`](#segment-config-options) Cache or Opt out Cache or Opt out [`cookies`](#cookies) Revalidate (Server Action) Opt out [`headers`, `searchParams`](#dynamic-functions) Opt out [`generateStaticParams`](#generatestaticparams) Cache [`React.cache`](#react-cache-function) Cache [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) ### [`<Link>`](#link) By default, the `<Link>` component automatically prefetches routes from the Full Route Cache and adds the React Server Component Payload to the Router Cache. To disable prefetching, you can set the `prefetch` prop to `false`. But this will not skip the cache permanently, the route segment will still be cached client-side when the user visits the route. Learn more about the [`<Link>` component](/docs/app/api-reference/components/link). ### [`router.prefetch`](#routerprefetch) The `prefetch` option of the `useRouter` hook can be used to manually prefetch a route. This adds the React Server Component Payload to the Router Cache. See the [`useRouter` hook](/docs/app/api-reference/functions/use-router) API reference. ### [`router.refresh`](#routerrefresh) The `refresh` option of the `useRouter` hook can be used to manually refresh a route. This completely clears the Router Cache, and makes a new request to the server for the current route. `refresh` does not affect the Data or Full Route Cache. The rendered result will be reconciled on the client while preserving React state and browser state. See the [`useRouter` hook](/docs/app/api-reference/functions/use-router) API reference. ### [`fetch`](#fetch) Data returned from `fetch` is automatically cached in the Data Cache. // Cached by default. `force-cache` is the default option and can be omitted. fetch(`https://...`, { cache: 'force-cache' }) See the [`fetch` API Reference](/docs/app/api-reference/functions/fetch) for more options. ### [`fetch options.cache`](#fetch-optionscache) You can opt out individual `fetch` requests of data caching by setting the `cache` option to `no-store`: // Opt out of caching fetch(`https://...`, { cache: 'no-store' }) Since the render output depends on data, using `cache: 'no-store'` will also skip the Full Route Cache for the route where the `fetch` request is used. That is, the route will be dynamically rendered every request, but you can still have other cached data requests in the same route. See the [`fetch` API Reference](/docs/app/api-reference/functions/fetch) for more options. ### [`fetch options.next.revalidate`](#fetch-optionsnextrevalidate) You can use the `next.revalidate` option of `fetch` to set the revalidation period (in seconds) of an individual `fetch` request. This will revalidate the Data Cache, which in turn will revalidate the Full Route Cache. Fresh data will be fetched, and components will be re-rendered on the server. // Revalidate at most after 1 hour fetch(`https://...`, { next: { revalidate: 3600 } }) See the [`fetch` API reference](/docs/app/api-reference/functions/fetch) for more options. ### [`fetch options.next.tags` and `revalidateTag`](#fetch-optionsnexttags-and-revalidatetag) Next.js has a cache tagging system for fine-grained data caching and revalidation. 1. When using `fetch` or [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache), you have the option to tag cache entries with one or more tags. 2. Then, you can call `revalidateTag` to purge the cache entries associated with that tag. For example, you can set a tag when fetching data: // Cache data with a tag fetch(`https://...`, { next: { tags: ['a', 'b', 'c'] } }) Then, call `revalidateTag` with a tag to purge the cache entry: // Revalidate entries with a specific tag revalidateTag('a') There are two places you can use `revalidateTag`, depending on what you're trying to achieve: 1. [Route Handlers](/docs/app/building-your-application/routing/route-handlers) - to revalidate data in response of a third party event (e.g. webhook). This will not invalidate the Router Cache immediately as the Router Handler isn't tied to a specific route. 2. [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) - to revalidate data after a user action (e.g. form submission). This will invalidate the Router Cache for the associated route. ### [`revalidatePath`](#revalidatepath) `revalidatePath` allows you manually revalidate data **and** re-render the route segments below a specific path in a single operation. Calling the `revalidatePath` method revalidates the Data Cache, which in turn invalidates the Full Route Cache. revalidatePath('/') There are two places you can use `revalidatePath`, depending on what you're trying to achieve: 1. [Route Handlers](/docs/app/building-your-application/routing/route-handlers) - to revalidate data in response to a third party event (e.g. webhook). 2. [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) - to revalidate data after a user interaction (e.g. form submission, clicking a button). See the [`revalidatePath` API reference](/docs/app/api-reference/functions/revalidatePath) for more information. > **`revalidatePath`** vs. **`router.refresh`**: > > Calling `router.refresh` will clear the Router cache, and re-render route segments on the server without invalidating the Data Cache or the Full Route Cache. > > The difference is that `revalidatePath` purges the Data Cache and Full Route Cache, whereas `router.refresh()` does not change the Data Cache and Full Route Cache, as it is a client-side API. ### [Dynamic Functions](#dynamic-functions) Dynamic functions like `cookies` and `headers`, and the `searchParams` prop in Pages depend on runtime incoming request information. Using them will opt a route out of the Full Route Cache, in other words, the route will be dynamically rendered. #### [`cookies`](#cookies) Using `cookies.set` or `cookies.delete` in a Server Action invalidates the Router Cache to prevent routes that use cookies from becoming stale (e.g. to reflect authentication changes). See the [`cookies`](/docs/app/api-reference/functions/cookies) API reference. ### [Segment Config Options](#segment-config-options) The Route Segment Config options can be used to override the route segment defaults or when you're not able to use the `fetch` API (e.g. database client or 3rd party libraries). The following Route Segment Config options will opt out of the Data Cache and Full Route Cache: * `const dynamic = 'force-dynamic'` * `const revalidate = 0` See the [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) documentation for more options. ### [`generateStaticParams`](#generatestaticparams) For [dynamic segments](/docs/app/building-your-application/routing/dynamic-routes) (e.g. `app/blog/[slug]/page.js`), paths provided by `generateStaticParams` are cached in the Full Route Cache at build time. At request time, Next.js will also cache paths that weren't known at build time the first time they're visited. You can disable caching at request time by using `export const dynamicParams = false` option in a route segment. When this config option is used, only paths provided by `generateStaticParams` will be served, and other routes will 404 or match (in the case of [catch-all routes](/docs/app/building-your-application/routing/dynamic-routes#catch-all-segments)). See the [`generateStaticParams` API reference](/docs/app/api-reference/functions/generate-static-params). ### [React `cache` function](#react-cache-function) The React `cache` function allows you to memoize the return value of a function, allowing you to call the same function multiple times while only executing it once. Since `fetch` requests are automatically memoized, you do not need to wrap it in React `cache`. However, you can use `cache` to manually memoize data requests for use cases when the `fetch` API is not suitable. For example, some database clients, CMS clients, or GraphQL clients. utils/get-item.ts TypeScript JavaScriptTypeScript import { cache } from 'react' import db from '@/lib/db' export const getItem = cache(async (id: string) => { const item = await db.item.findUnique({ id }) return item }) [Previous Edge and Node.js Runtimes ](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) [Next Styling ](/docs/app/building-your-application/styling) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e8cffc30597915af02d8896a97ccc17d\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/draft-mode
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [ draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/draft-mode.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)draftMode draftMode ========= The `draftMode` function allows you to detect [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) inside a [Server Component](/docs/app/building-your-application/rendering/server-components). app/page.js import { draftMode } from 'next/headers' export default function Page() { const { isEnabled } = draftMode() return ( <main> <h1>My Blog Post</h1> <p>Draft Mode is currently {isEnabled ? 'Enabled' : 'Disabled'}</p> </main> ) } [Version History](#version-history) ----------------------------------- Version Changes `v13.4.0` `draftMode` introduced. [Previous cookies ](/docs/app/api-reference/functions/cookies) [Next fetch ](/docs/app/api-reference/functions/fetch) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"220ec96a3fa4ff6bd9abbfda980c4a84\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [ Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Runtime Differences](#runtime-differences) * [Edge Runtime](#edge-runtime) * [Node.js Runtime](#nodejs-runtime) * [Serverless Node.js](#serverless-nodejs) * [Examples](#examples) * [Segment Runtime Option](#segment-runtime-option) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/03-rendering/04-edge-and-nodejs-runtimes.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Rendering](/docs/app/building-your-application/rendering)Edge and Node.js Runtimes Edge and Node.js Runtimes ========================= In the context of Next.js, runtime refers to the set of libraries, APIs, and general functionality available to your code during execution. On the server, there are two runtimes where parts of your application code can be rendered: * The **Node.js Runtime** (default) has access to all Node.js APIs and compatible packages from the ecosystem. * The **Edge Runtime** is based on [Web APIs](/docs/app/api-reference/edge). [Runtime Differences](#runtime-differences) ------------------------------------------- There are many considerations to make when choosing a runtime. This table shows the major differences at a glance. If you want a more in-depth analysis of the differences, check out the sections below. Node Serverless Edge Cold Boot / Normal Low [HTTP Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) Yes Yes Yes IO All All `fetch` Scalability / High Highest Security Normal High High Latency Normal Low Lowest npm Packages All All A smaller subset [Static Rendering](/docs/app/building-your-application/rendering/server-components#static-rendering-default) Yes Yes No [Dynamic Rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) Yes Yes Yes [Data Revalidation w/ `fetch`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) Yes Yes Yes ### [Edge Runtime](#edge-runtime) In Next.js, the lightweight Edge Runtime is a subset of available Node.js APIs. The Edge Runtime is ideal if you need to deliver dynamic, personalized content at low latency with small, simple functions. The Edge Runtime's speed comes from its minimal use of resources, but that can be limiting in many scenarios. For example, code executed in the Edge Runtime [on Vercel cannot exceed between 1 MB and 4 MB](https://vercel.com/docs/concepts/limits/overview#edge-middleware-and-edge-functions-size), this limit includes imported packages, fonts and files, and will vary depending on your deployment infrastructure. In addition, the Edge Runtime does not support all Node.js APIs meaning some `npm` packages may not work. For example, "Module not found: Can't resolve 'fs'" or similar errors. We recommend using the Node.js runtime if you need to use these APIs or packages. ### [Node.js Runtime](#nodejs-runtime) Using the Node.js runtime gives you access to all Node.js APIs, and all npm packages that rely on them. However, it's not as fast to start up as routes using the Edge runtime. Deploying your Next.js application to a Node.js server will require managing, scaling, and configuring your infrastructure. Alternatively, you can consider deploying your Next.js application to a serverless platform like Vercel, which will handle this for you. ### [Serverless Node.js](#serverless-nodejs) Serverless is ideal if you need a scalable solution that can handle more complex computational loads than the Edge Runtime. With Serverless Functions on Vercel, for example, your overall code size is [50MB](https://vercel.com/docs/concepts/limits/overview#serverless-function-size) including imported packages, fonts, and files. The downside compared to routes using the [Edge](https://vercel.com/docs/concepts/functions/edge-functions) is that it can take hundreds of milliseconds for Serverless Functions to boot up before they begin processing requests. Depending on the amount of traffic your site receives, this could be a frequent occurrence as the functions are not frequently "warm". [Examples](#examples) --------------------- ### [Segment Runtime Option](#segment-runtime-option) You can specify a runtime for individual route segments in your Next.js application. To do so, [declare a variable called `runtime` and export it](/docs/app/api-reference/file-conventions/route-segment-config). The variable must be a string, and must have a value of either `'nodejs'` or `'edge'` runtime. The following example demonstrates a page route segment that exports a `runtime` with a value of `'edge'`: app/page.tsx TypeScript JavaScriptTypeScript export const runtime = 'edge' // 'nodejs' (default) | 'edge' You can also define `runtime` on a layout level, which will make all routes under the layout run on the edge runtime: app/layout.tsx TypeScript JavaScriptTypeScript export const runtime = 'edge' // 'nodejs' (default) | 'edge' If the segment runtime is _not_ set, the default `nodejs` runtime will be used. You do not need to use the `runtime` option if you do not plan to change from the Node.js runtime. > Please refer to the [Node.js Docs](https://nodejs.org/docs/latest/api/) and [Edge Docs](/docs/app/api-reference/edge) for the full list of available APIs. Both runtimes can also support [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) depending on your deployment infrastructure. [Previous Composition Patterns ](/docs/app/building-your-application/rendering/composition-patterns) [Next Caching ](/docs/app/building-your-application/caching) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e957a7a9f7f917d622985b28598c571b\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/fetch
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [ fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [fetch(url, options)](#fetchurl-options) * [options.cache](#optionscache) * [options.next.revalidate](#optionsnextrevalidate) * [options.next.tags](#optionsnexttags) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/fetch.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)fetch fetch ===== Next.js extends the native [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow each request on the server to set its own persistent caching semantics. In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent HTTP cache. You can call `fetch` with `async` and `await` directly within Server Components. app/page.tsx TypeScript JavaScriptTypeScript export default async function Page() { // This request should be cached until manually invalidated. // Similar to `getStaticProps`. // `force-cache` is the default and can be omitted. const staticData = await fetch(`https://...`, { cache: 'force-cache' }) // This request should be refetched on every request. // Similar to `getServerSideProps`. const dynamicData = await fetch(`https://...`, { cache: 'no-store' }) // This request should be cached with a lifetime of 10 seconds. // Similar to `getStaticProps` with the `revalidate` option. const revalidatedData = await fetch(`https://...`, { next: { revalidate: 10 }, }) return <div>...</div> } [`fetch(url, options)`](#fetchurl-options) ------------------------------------------ Since Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API), you can use any of the [native options available](https://developer.mozilla.org/docs/Web/API/fetch#parameters). ### [`options.cache`](#optionscache) Configure how the request should interact with Next.js [Data Cache](/docs/app/building-your-application/caching#data-cache). fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) * **`force-cache`** (default) - Next.js looks for a matching request in its Data Cache. * If there is a match and it is fresh, it will be returned from the cache. * If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource. * **`no-store`** - Next.js fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource. > **Good to know**: > > * If you don't provide a `cache` option, Next.js will default to `force-cache`, unless a [dynamic function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions) such as `cookies()` is used, in which case it will default to `no-store`. > * The `no-cache` option behaves the same way as `no-store` in Next.js. ### [`options.next.revalidate`](#optionsnextrevalidate) fetch(`https://...`, { next: { revalidate: false | 0 | number } }) Set the cache lifetime of a resource (in seconds). * **`false`** - Cache the resource indefinitely. Semantically equivalent to `revalidate: Infinity`. The HTTP cache may evict older resources over time. * **`0`** - Prevent the resource from being cached. * **`number`** - (in seconds) Specify the resource should have a cache lifetime of at most `n` seconds. > **Good to know**: > > * If an individual `fetch()` request sets a `revalidate` number lower than the [default `revalidate`](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) of a route, the whole route revalidation interval will be decreased. > * If two fetch requests with the same URL in the same route have different `revalidate` values, the lower value will be used. > * As a convenience, it is not necessary to set the `cache` option if `revalidate` is set to a number since `0` implies `cache: 'no-store'` and a positive value implies `cache: 'force-cache'`. > * Conflicting options such as `{ revalidate: 0, cache: 'force-cache' }` or `{ revalidate: 10, cache: 'no-store' }` will cause an error. ### [`options.next.tags`](#optionsnexttags) fetch(`https://...`, { next: { tags: ['collection'] } }) Set the cache tags of a resource. Data can then be revalidated on-demand using [`revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag). The max length for a custom tag is 256 characters and the max tag items is 64. [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `fetch` introduced. [Previous draftMode ](/docs/app/api-reference/functions/draft-mode) [Next generateImageMetadata ](/docs/app/api-reference/functions/generate-image-metadata) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"b55fc8aa3fd6c0ff4438d0b4211588ea\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [ generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Parameters](#parameters) * [params (optional)](#params-optional) * [Returns](#returns) * [Examples](#examples) * [Using external data](#using-external-data) * [Version History](#version-history) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/generate-image-metadata.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)generateImageMetadata generateImageMetadata ===================== You can use `generateImageMetadata` to generate different versions of one image or return multiple images for one route segment. This is useful for when you want to avoid hard-coding metadata values, such as for icons. [Parameters](#parameters) ------------------------- `generateImageMetadata` function accepts the following parameters: #### [`params` (optional)](#params-optional) An object containing the [dynamic route parameters](/docs/app/building-your-application/routing/dynamic-routes) object from the root segment down to the segment `generateImageMetadata` is called from. icon.tsx TypeScript JavaScriptTypeScript export function generateImageMetadata({ params, }: { params: { slug: string } }) { // ... } Route URL `params` `app/shop/icon.js` `/shop` `undefined` `app/shop/[slug]/icon.js` `/shop/1` `{ slug: '1' }` `app/shop/[tag]/[item]/icon.js` `/shop/1/2` `{ tag: '1', item: '2' }` `app/shop/[...slug]/icon.js` `/shop/1/2` `{ slug: ['1', '2'] }` [Returns](#returns) ------------------- The `generateImageMetadata` function should return an `array` of objects containing the image's metadata such as `alt` and `size`. In addition, each item **must** include an `id` value which will be passed to the props of the image generating function. Image Metadata Object Type `id` `string` (required) `alt` `string` `size` `{ width: number; height: number }` `contentType` `string` icon.tsx TypeScript JavaScriptTypeScript import { ImageResponse } from 'next/og' export function generateImageMetadata() { return [ { contentType: 'image/png', size: { width: 48, height: 48 }, id: 'small', }, { contentType: 'image/png', size: { width: 72, height: 72 }, id: 'medium', }, ] } export default function Icon({ id }: { id: string }) { return new ImageResponse( ( <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 88, background: '#000', color: '#fafafa', }} > Icon {id} </div> ) ) } ### [Examples](#examples) #### [Using external data](#using-external-data) This example uses the `params` object and external data to generate multiple [Open Graph images](/docs/app/api-reference/file-conventions/metadata/opengraph-image) for a route segment. app/products/\[id\]/opengraph-image.tsx TypeScript JavaScriptTypeScript import { ImageResponse } from 'next/og' import { getCaptionForImage, getOGImages } from '@/app/utils/images' export async function generateImageMetadata({ params, }: { params: { id: string } }) { const images = await getOGImages(params.id) return images.map((image, idx) => ({ id: idx, size: { width: 1200, height: 600 }, alt: image.text, contentType: 'image/png', })) } export default async function Image({ params, id, }: { params: { id: string } id: number }) { const productId = params.id const imageId = id const text = await getCaptionForImage(productId, imageId) return new ImageResponse( ( <div style={ { // ... } } > {text} </div> ) ) } [Version History](#version-history) ----------------------------------- Version Changes `v13.3.0` `generateImageMetadata` introduced. Next Steps ---------- View all the Metadata API options. [ App Router ... File Conventions ### Metadata Files API documentation for the metadata file conventions. ](/docs/app/api-reference/file-conventions/metadata)[ App Router ... Optimizing ### Metadata Use the Metadata API to define metadata in any layout or page. ](/docs/app/building-your-application/optimizing/metadata) [Previous fetch ](/docs/app/api-reference/functions/fetch) [Next generateMetadata ](/docs/app/api-reference/functions/generate-metadata) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"427f731f3006bfd9a151e76e6cc4317e\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/getting-started/project-structure
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Top-level folders](#top-level-folders) * [Top-level files](#top-level-files) * [app Routing Conventions](#app-routing-conventions) * [Routing Files](#routing-files) * [Nested Routes](#nested-routes) * [Dynamic Routes](#dynamic-routes) * [Route Groups and Private Folders](#route-groups-and-private-folders) * [Parallel and Intercepted Routes](#parallel-and-intercepted-routes) * [Metadata File Conventions](#metadata-file-conventions) * [App Icons](#app-icons) * [Open Graph and Twitter Images](#open-graph-and-twitter-images) * [SEO](#seo) * [pages Routing Conventions](#pages-routing-conventions) * [Special Files](#special-files) * [Routes](#routes) * [Dynamic Routes](#dynamic-routes-1) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/01-getting-started/02-project-structure.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [Getting Started](/docs/getting-started)Project Structure Next.js Project Structure ========================= This page provides an overview of the project structure of a Next.js application. It covers top-level files and folders, configuration files, and routing conventions within the `app` and `pages` directories. Click the file and folder names to learn more about each convention. [Top-level folders](#top-level-folders) --------------------------------------- Top-level folders are used to organize your application's code and static assets. ![Route segments to path segments](/_next/image?url=%2Fdocs%2Flight%2Ftop-level-folders.png&w=3840&q=75)![Route segments to path segments](/_next/image?url=%2Fdocs%2Fdark%2Ftop-level-folders.png&w=3840&q=75) [`app`](/docs/app/building-your-application/routing) App Router [`pages`](/docs/pages/building-your-application/routing) Pages Router [`public`](/docs/app/building-your-application/optimizing/static-assets) Static assets to be served [`src`](/docs/app/building-your-application/configuring/src-directory) Optional application source folder [Top-level files](#top-level-files) ----------------------------------- Top-level files are used to configure your application, manage dependencies, run middleware, integrate monitoring tools, and define environment variables. **Next.js** [`next.config.js`](/docs/app/api-reference/next-config-js) Configuration file for Next.js [`package.json`](/docs/getting-started/installation#manual-installation) Project dependencies and scripts [`instrumentation.ts`](/docs/app/building-your-application/optimizing/instrumentation) OpenTelemetry and Instrumentation file [`middleware.ts`](/docs/app/building-your-application/routing/middleware) Next.js request middleware [`.env`](/docs/app/building-your-application/configuring/environment-variables) Environment variables [`.env.local`](/docs/app/building-your-application/configuring/environment-variables) Local environment variables [`.env.production`](/docs/app/building-your-application/configuring/environment-variables) Production environment variables [`.env.development`](/docs/app/building-your-application/configuring/environment-variables) Development environment variables [`.eslintrc.json`](/docs/app/building-your-application/configuring/eslint) Configuration file for ESLint `.gitignore` Git files and folders to ignore `next-env.d.ts` TypeScript declaration file for Next.js `tsconfig.json` Configuration file for TypeScript `jsconfig.json` Configuration file for JavaScript [`app` Routing Conventions](#app-routing-conventions) ----------------------------------------------------- The following file conventions are used to define routes and handle metadata in the [`app` router](/docs/app). ### [Routing Files](#routing-files) [`layout`](/docs/app/api-reference/file-conventions/layout) `.js` `.jsx` `.tsx` Layout [`page`](/docs/app/api-reference/file-conventions/page) `.js` `.jsx` `.tsx` Page [`loading`](/docs/app/api-reference/file-conventions/loading) `.js` `.jsx` `.tsx` Loading UI [`not-found`](/docs/app/api-reference/file-conventions/not-found) `.js` `.jsx` `.tsx` Not found UI [`error`](/docs/app/api-reference/file-conventions/error) `.js` `.jsx` `.tsx` Error UI [`global-error`](/docs/app/api-reference/file-conventions/error#global-errorjs) `.js` `.jsx` `.tsx` Global error UI [`route`](/docs/app/api-reference/file-conventions/route) `.js` `.ts` API endpoint [`template`](/docs/app/api-reference/file-conventions/template) `.js` `.jsx` `.tsx` Re-rendered layout [`default`](/docs/app/api-reference/file-conventions/default) `.js` `.jsx` `.tsx` Parallel route fallback page ### [Nested Routes](#nested-routes) [`folder`](/docs/app/building-your-application/routing#route-segments) Route segment [`folder/folder`](/docs/app/building-your-application/routing#nested-routes) Nested route segment ### [Dynamic Routes](#dynamic-routes) [`[folder]`](/docs/app/building-your-application/routing/dynamic-routes#convention) Dynamic route segment [`[...folder]`](/docs/app/building-your-application/routing/dynamic-routes#catch-all-segments) Catch-all route segment [`[[...folder]]`](/docs/app/building-your-application/routing/dynamic-routes#optional-catch-all-segments) Optional catch-all route segment ### [Route Groups and Private Folders](#route-groups-and-private-folders) [`(folder)`](/docs/app/building-your-application/routing/route-groups#convention) Group routes without affecting routing [`_folder`](/docs/app/building-your-application/routing/colocation#private-folders) Opt folder and all child segments out of routing ### [Parallel and Intercepted Routes](#parallel-and-intercepted-routes) [`@folder`](/docs/app/building-your-application/routing/parallel-routes#slots) Named slot [`(.)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) Intercept same level [`(..)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) Intercept one level above [`(..)(..)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) Intercept two levels above [`(...)folder`](/docs/app/building-your-application/routing/intercepting-routes#convention) Intercept from root ### [Metadata File Conventions](#metadata-file-conventions) #### [App Icons](#app-icons) [`favicon`](/docs/app/api-reference/file-conventions/metadata/app-icons#favicon) `.ico` Favicon file [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#icon) `.ico` `.jpg` `.jpeg` `.png` `.svg` App Icon file [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) `.js` `.ts` `.tsx` Generated App Icon [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#apple-icon) `.jpg` `.jpeg`, `.png` Apple App Icon file [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) `.js` `.ts` `.tsx` Generated Apple App Icon #### [Open Graph and Twitter Images](#open-graph-and-twitter-images) [`opengraph-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#opengraph-image) `.jpg` `.jpeg` `.png` `.gif` Open Graph image file [`opengraph-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#generate-images-using-code-js-ts-tsx) `.js` `.ts` `.tsx` Generated Open Graph image [`twitter-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#twitter-image) `.jpg` `.jpeg` `.png` `.gif` Twitter image file [`twitter-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#generate-images-using-code-js-ts-tsx) `.js` `.ts` `.tsx` Generated Twitter image #### [SEO](#seo) [`sitemap`](/docs/app/api-reference/file-conventions/metadata/sitemap#sitemap-files-xml) `.xml` Sitemap file [`sitemap`](/docs/app/api-reference/file-conventions/metadata/sitemap#generating-a-sitemap-using-code-js-ts) `.js` `.ts` Generated Sitemap [`robots`](/docs/app/api-reference/file-conventions/metadata/robots#static-robotstxt) `.txt` Robots file [`robots`](/docs/app/api-reference/file-conventions/metadata/robots#generate-a-robots-file) `.js` `.ts` Generated Robots file [`pages` Routing Conventions](#pages-routing-conventions) --------------------------------------------------------- The following file conventions are used to define routes in the [`pages` router](/docs/pages). ### [Special Files](#special-files) [`_app`](/docs/pages/building-your-application/routing/custom-app) `.js` `.jsx` `.tsx` Custom App [`_document`](/docs/pages/building-your-application/routing/custom-document) `.js` `.jsx` `.tsx` Custom Document [`_error`](/docs/pages/building-your-application/routing/custom-error#more-advanced-error-page-customizing) `.js` `.jsx` `.tsx` Custom Error Page [`404`](/docs/pages/building-your-application/routing/custom-error#404-page) `.js` `.jsx` `.tsx` 404 Error Page [`500`](/docs/pages/building-your-application/routing/custom-error#500-page) `.js` `.jsx` `.tsx` 500 Error Page ### [Routes](#routes) **Folder convention** [`index`](/docs/pages/building-your-application/routing/pages-and-layouts#index-routes) `.js` `.jsx` `.tsx` Home page [`folder/index`](/docs/pages/building-your-application/routing/pages-and-layouts#index-routes) `.js` `.jsx` `.tsx` Nested page **File convention** [`index`](/docs/pages/building-your-application/routing/pages-and-layouts#index-routes) `.js` `.jsx` `.tsx` Home page [`file`](/docs/pages/building-your-application/routing/pages-and-layouts) `.js` `.jsx` `.tsx` Nested page ### [Dynamic Routes](#dynamic-routes-1) **Folder convention** [`[folder]/index`](/docs/pages/building-your-application/routing/dynamic-routes) `.js` `.jsx` `.tsx` Dynamic route segment [`[...folder]/index`](/docs/pages/building-your-application/routing/dynamic-routes#catch-all-segments) `.js` `.jsx` `.tsx` Catch-all route segment [`[[...folder]]/index`](/docs/pages/building-your-application/routing/dynamic-routes#optional-catch-all-segments) `.js` `.jsx` `.tsx` Optional catch-all route segment **File convention** [`[file]`](/docs/pages/building-your-application/routing/dynamic-routes) `.js` `.jsx` `.tsx` Dynamic route segment [`[...file]`](/docs/pages/building-your-application/routing/dynamic-routes#catch-all-segments) `.js` `.jsx` `.tsx` Catch-all route segment [`[[...file]]`](/docs/pages/building-your-application/routing/dynamic-routes#optional-catch-all-segments) `.js` `.jsx` `.tsx` Optional catch-all route segment [Previous Installation ](/docs/getting-started/installation) [Next App Router ](/docs/app) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"c774ada559073094bd2d6e44b98c2c46\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Terminology](#terminology) * [The app Router](#the-app-router) * [Roles of Folders and Files](#roles-of-folders-and-files) * [Route Segments](#route-segments) * [Nested Routes](#nested-routes) * [File Conventions](#file-conventions) * [Component Hierarchy](#component-hierarchy) * [Colocation](#colocation) * [Advanced Routing Patterns](#advanced-routing-patterns) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Routing Routing Fundamentals ==================== The skeleton of every application is routing. This page will introduce you to the **fundamental concepts** of routing for the web and how to handle routing in Next.js. [Terminology](#terminology) --------------------------- First, you will see these terms being used throughout the documentation. Here's a quick reference: ![Terminology for Component Tree](/_next/image?url=%2Fdocs%2Flight%2Fterminology-component-tree.png&w=3840&q=75)![Terminology for Component Tree](/_next/image?url=%2Fdocs%2Fdark%2Fterminology-component-tree.png&w=3840&q=75) * **Tree:** A convention for visualizing a hierarchical structure. For example, a component tree with parent and children components, a folder structure, etc. * **Subtree:** Part of a tree, starting at a new root (first) and ending at the leaves (last). * **Root**: The first node in a tree or subtree, such as a root layout. * **Leaf:** Nodes in a subtree that have no children, such as the last segment in a URL path. ![Terminology for URL Anatomy](/_next/image?url=%2Fdocs%2Flight%2Fterminology-url-anatomy.png&w=3840&q=75)![Terminology for URL Anatomy](/_next/image?url=%2Fdocs%2Fdark%2Fterminology-url-anatomy.png&w=3840&q=75) * **URL Segment:** Part of the URL path delimited by slashes. * **URL Path:** Part of the URL that comes after the domain (composed of segments). [The `app` Router](#the-app-router) ----------------------------------- In version 13, Next.js introduced a new **App Router** built on [React Server Components](/docs/app/building-your-application/rendering/server-components), which supports shared layouts, nested routing, loading states, error handling, and more. The App Router works in a new directory named `app`. The `app` directory works alongside the `pages` directory to allow for incremental adoption. This allows you to opt some routes of your application into the new behavior while keeping other routes in the `pages` directory for previous behavior. If your application uses the `pages` directory, please also see the [Pages Router](/docs/pages/building-your-application/routing) documentation. > **Good to know**: The App Router takes priority over the Pages Router. Routes across directories should not resolve to the same URL path and will cause a build-time error to prevent a conflict. ![Next.js App Directory](/_next/image?url=%2Fdocs%2Flight%2Fnext-router-directories.png&w=3840&q=75)![Next.js App Directory](/_next/image?url=%2Fdocs%2Fdark%2Fnext-router-directories.png&w=3840&q=75) By default, components inside `app` are [React Server Components](/docs/app/building-your-application/rendering/server-components). This is a performance optimization and allows you to easily adopt them, and you can also use [Client Components](/docs/app/building-your-application/rendering/client-components). > **Recommendation:** Check out the [Server](/docs/app/building-your-application/rendering/server-components) page if you're new to Server Components. [Roles of Folders and Files](#roles-of-folders-and-files) --------------------------------------------------------- Next.js uses a file-system based router where: * **Folders** are used to define routes. A route is a single path of nested folders, following the file-system hierarchy from the **root folder** down to a final **leaf folder** that includes a `page.js` file. See [Defining Routes](/docs/app/building-your-application/routing/defining-routes). * **Files** are used to create UI that is shown for a route segment. See [special files](#file-conventions). [Route Segments](#route-segments) --------------------------------- Each folder in a route represents a **route segment**. Each route segment is mapped to a corresponding **segment** in a **URL path**. ![How Route Segments Map to URL Segments](/_next/image?url=%2Fdocs%2Flight%2Froute-segments-to-path-segments.png&w=3840&q=75)![How Route Segments Map to URL Segments](/_next/image?url=%2Fdocs%2Fdark%2Froute-segments-to-path-segments.png&w=3840&q=75) [Nested Routes](#nested-routes) ------------------------------- To create a nested route, you can nest folders inside each other. For example, you can add a new `/dashboard/settings` route by nesting two new folders in the `app` directory. The `/dashboard/settings` route is composed of three segments: * `/` (Root segment) * `dashboard` (Segment) * `settings` (Leaf segment) [File Conventions](#file-conventions) ------------------------------------- Next.js provides a set of special files to create UI with specific behavior in nested routes: [`layout`](/docs/app/building-your-application/routing/pages-and-layouts#layouts) Shared UI for a segment and its children [`page`](/docs/app/building-your-application/routing/pages-and-layouts#pages) Unique UI of a route and make routes publicly accessible [`loading`](/docs/app/building-your-application/routing/loading-ui-and-streaming) Loading UI for a segment and its children [`not-found`](/docs/app/api-reference/file-conventions/not-found) Not found UI for a segment and its children [`error`](/docs/app/building-your-application/routing/error-handling) Error UI for a segment and its children [`global-error`](/docs/app/building-your-application/routing/error-handling) Global Error UI [`route`](/docs/app/building-your-application/routing/route-handlers) Server-side API endpoint [`template`](/docs/app/building-your-application/routing/pages-and-layouts#templates) Specialized re-rendered Layout UI [`default`](/docs/app/api-reference/file-conventions/default) Fallback UI for [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) > **Good to know**: `.js`, `.jsx`, or `.tsx` file extensions can be used for special files. [Component Hierarchy](#component-hierarchy) ------------------------------------------- The React components defined in special files of a route segment are rendered in a specific hierarchy: * `layout.js` * `template.js` * `error.js` (React error boundary) * `loading.js` (React suspense boundary) * `not-found.js` (React error boundary) * `page.js` or nested `layout.js` ![Component Hierarchy for File Conventions](/_next/image?url=%2Fdocs%2Flight%2Ffile-conventions-component-hierarchy.png&w=3840&q=75)![Component Hierarchy for File Conventions](/_next/image?url=%2Fdocs%2Fdark%2Ffile-conventions-component-hierarchy.png&w=3840&q=75) In a nested route, the components of a segment will be nested **inside** the components of its parent segment. ![Nested File Conventions Component Hierarchy](/_next/image?url=%2Fdocs%2Flight%2Fnested-file-conventions-component-hierarchy.png&w=3840&q=75)![Nested File Conventions Component Hierarchy](/_next/image?url=%2Fdocs%2Fdark%2Fnested-file-conventions-component-hierarchy.png&w=3840&q=75) [Colocation](#colocation) ------------------------- In addition to special files, you have the option to colocate your own files (e.g. components, styles, tests, etc) inside folders in the `app` directory. This is because while folders define routes, only the contents returned by `page.js` or `route.js` are publicly addressable. ![An example folder structure with colocated files](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-colocation.png&w=3840&q=75)![An example folder structure with colocated files](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-colocation.png&w=3840&q=75) Learn more about [Project Organization and Colocation](/docs/app/building-your-application/routing/colocation). [Advanced Routing Patterns](#advanced-routing-patterns) ------------------------------------------------------- The App Router also provides a set of conventions to help you implement more advanced routing patterns. These include: * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes): Allow you to simultaneously show two or more pages in the same view that can be navigated independently. You can use them for split views that have their own sub-navigation. E.g. Dashboards. * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes): Allow you to intercept a route and show it in the context of another route. You can use these when keeping the context for the current page is important. E.g. Seeing all tasks while editing one task or expanding a photo in a feed. These patterns allow you to build richer and more complex UIs, democratizing features that were historically complex for small teams and individual developers to implement. [Next Steps](#next-steps) ------------------------- Now that you understand the fundamentals of routing in Next.js, follow the links below to create your first routes: [ ### Defining Routes Learn how to create your first route in Next.js. ](/docs/app/building-your-application/routing/defining-routes)[ ### Pages and Layouts Create your first page and shared layout with the App Router. ](/docs/app/building-your-application/routing/pages-and-layouts)[ ### Linking and Navigating Learn how navigation works in Next.js, and how to use the Link Component and \`useRouter\` hook. ](/docs/app/building-your-application/routing/linking-and-navigating)[ ### Loading UI and Streaming Built on top of Suspense, Loading UI allows you to create a fallback for specific route segments, and automatically stream content as it becomes ready. ](/docs/app/building-your-application/routing/loading-ui-and-streaming)[ ### Error Handling Handle runtime errors by automatically wrapping route segments and their nested children in a React Error Boundary. ](/docs/app/building-your-application/routing/error-handling)[ ### Redirecting Learn the different ways to handle redirects in Next.js. ](/docs/app/building-your-application/routing/redirecting)[ ### Route Groups Route Groups can be used to partition your Next.js application into different sections. ](/docs/app/building-your-application/routing/route-groups)[ ### Project Organization Learn how to organize your Next.js project and colocate files. ](/docs/app/building-your-application/routing/colocation)[ ### Dynamic Routes Dynamic Routes can be used to programmatically generate route segments from dynamic data. ](/docs/app/building-your-application/routing/dynamic-routes)[ ### Parallel Routes Simultaneously render one or more pages in the same view that can be navigated independently. A pattern for highly dynamic applications. ](/docs/app/building-your-application/routing/parallel-routes)[ ### Intercepting Routes Use intercepting routes to load a new route within the current layout while masking the browser URL, useful for advanced routing patterns such as modals. ](/docs/app/building-your-application/routing/intercepting-routes)[ ### Route Handlers Create custom request handlers for a given route using the Web's Request and Response APIs. ](/docs/app/building-your-application/routing/route-handlers)[ ### Middleware Learn how to use Middleware to run code before a request is completed. ](/docs/app/building-your-application/routing/middleware)[ ### Internationalization Add support for multiple languages with internationalized routing and localized content. ](/docs/app/building-your-application/routing/internationalization) [Previous Building Your Application ](/docs/app/building-your-application) [Next Defining Routes ](/docs/app/building-your-application/routing/defining-routes) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"026db591317deb315d4336e75d24d57d\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [ Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [When to use Server and Client Components?](#when-to-use-server-and-client-components) * [Server Component Patterns](#server-component-patterns) * [Sharing data between components](#sharing-data-between-components) * [Keeping Server-only Code out of the Client Environment](#keeping-server-only-code-out-of-the-client-environment) * [Using Third-party Packages and Providers](#using-third-party-packages-and-providers) * [Using Context Providers](#using-context-providers) * [Advice for Library Authors](#advice-for-library-authors) * [Client Components](#client-components) * [Moving Client Components Down the Tree](#moving-client-components-down-the-tree) * [Passing props from Server to Client Components (Serialization)](#passing-props-from-server-to-client-components-serialization) * [Interleaving Server and Client Components](#interleaving-server-and-client-components) * [Unsupported Pattern: Importing Server Components into Client Components](#unsupported-pattern-importing-server-components-into-client-components) * [Supported Pattern: Passing Server Components to Client Components as Props](#supported-pattern-passing-server-components-to-client-components-as-props) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/03-rendering/03-composition-patterns.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Rendering](/docs/app/building-your-application/rendering)Composition Patterns Server and Client Composition Patterns ====================================== When building React applications, you will need to consider what parts of your application should be rendered on the server or the client. This page covers some recommended composition patterns when using Server and Client Components. [When to use Server and Client Components?](#when-to-use-server-and-client-components) -------------------------------------------------------------------------------------- Here's a quick summary of the different use cases for Server and Client Components: What do you need to do? Server Component Client Component Fetch data Access backend resources (directly) Keep sensitive information on the server (access tokens, API keys, etc) Keep large dependencies on the server / Reduce client-side JavaScript Add interactivity and event listeners (`onClick()`, `onChange()`, etc) Use State and Lifecycle Effects (`useState()`, `useReducer()`, `useEffect()`, etc) Use browser-only APIs Use custom hooks that depend on state, effects, or browser-only APIs Use [React Class components](https://react.dev/reference/react/Component) [Server Component Patterns](#server-component-patterns) ------------------------------------------------------- Before opting into client-side rendering, you may wish to do some work on the server like fetching data, or accessing your database or backend services. Here are some common patterns when working with Server Components: ### [Sharing data between components](#sharing-data-between-components) When fetching data on the server, there may be cases where you need to share data across different components. For example, you may have a layout and a page that depend on the same data. Instead of using [React Context](https://react.dev/learn/passing-data-deeply-with-context) (which is not available on the server) or passing data as props, you can use [`fetch`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch) or React's `cache` function to fetch the same data in the components that need it, without worrying about making duplicate requests for the same data. This is because React extends `fetch` to automatically memoize data requests, and the `cache` function can be used when `fetch` is not available. Learn more about [memoization](/docs/app/building-your-application/caching#request-memoization) in React. ### [Keeping Server-only Code out of the Client Environment](#keeping-server-only-code-out-of-the-client-environment) Since JavaScript modules can be shared between both Server and Client Components modules, it's possible for code that was only ever intended to be run on the server to sneak its way into the client. For example, take the following data-fetching function: lib/data.ts TypeScript JavaScriptTypeScript export async function getData() { const res = await fetch('https://external-service.com/data', { headers: { authorization: process.env.API_KEY, }, }) return res.json() } At first glance, it appears that `getData` works on both the server and the client. However, this function contains an `API_KEY`, written with the intention that it would only ever be executed on the server. Since the environment variable `API_KEY` is not prefixed with `NEXT_PUBLIC`, it's a private variable that can only be accessed on the server. To prevent your environment variables from being leaked to the client, Next.js replaces private environment variables with an empty string. As a result, even though `getData()` can be imported and executed on the client, it won't work as expected. And while making the variable public would make the function work on the client, you may not want to expose sensitive information to the client. To prevent this sort of unintended client usage of server code, we can use the `server-only` package to give other developers a build-time error if they ever accidentally import one of these modules into a Client Component. To use `server-only`, first install the package: Terminal npm install server-only Then import the package into any module that contains server-only code: lib/data.js import 'server-only' export async function getData() { const res = await fetch('https://external-service.com/data', { headers: { authorization: process.env.API_KEY, }, }) return res.json() } Now, any Client Component that imports `getData()` will receive a build-time error explaining that this module can only be used on the server. The corresponding package `client-only` can be used to mark modules that contain client-only code – for example, code that accesses the `window` object. ### [Using Third-party Packages and Providers](#using-third-party-packages-and-providers) Since Server Components are a new React feature, third-party packages and providers in the ecosystem are just beginning to add the `"use client"` directive to components that use client-only features like `useState`, `useEffect`, and `createContext`. Today, many components from `npm` packages that use client-only features do not yet have the directive. These third-party components will work as expected within Client Components since they have the `"use client"` directive, but they won't work within Server Components. For example, let's say you've installed the hypothetical `acme-carousel` package which has a `<Carousel />` component. This component uses `useState`, but it doesn't yet have the `"use client"` directive. If you use `<Carousel />` within a Client Component, it will work as expected: app/gallery.tsx TypeScript JavaScriptTypeScript 'use client' import { useState } from 'react' import { Carousel } from 'acme-carousel' export default function Gallery() { let [isOpen, setIsOpen] = useState(false) return ( <div> <button onClick={() => setIsOpen(true)}>View pictures</button> {/* Works, since Carousel is used within a Client Component */} {isOpen && <Carousel />} </div> ) } However, if you try to use it directly within a Server Component, you'll see an error: app/page.tsx TypeScript JavaScriptTypeScript import { Carousel } from 'acme-carousel' export default function Page() { return ( <div> <p>View pictures</p> {/* Error: `useState` can not be used within Server Components */} <Carousel /> </div> ) } This is because Next.js doesn't know `<Carousel />` is using client-only features. To fix this, you can wrap third-party components that rely on client-only features in your own Client Components: app/carousel.tsx TypeScript JavaScriptTypeScript 'use client' import { Carousel } from 'acme-carousel' export default Carousel Now, you can use `<Carousel />` directly within a Server Component: app/page.tsx TypeScript JavaScriptTypeScript import Carousel from './carousel' export default function Page() { return ( <div> <p>View pictures</p> {/* Works, since Carousel is a Client Component */} <Carousel /> </div> ) } We don't expect you to need to wrap most third-party components since it's likely you'll be using them within Client Components. However, one exception is providers, since they rely on React state and context, and are typically needed at the root of an application. [Learn more about third-party context providers below](#using-context-providers). #### [Using Context Providers](#using-context-providers) Context providers are typically rendered near the root of an application to share global concerns, like the current theme. Since [React context](https://react.dev/learn/passing-data-deeply-with-context) is not supported in Server Components, trying to create a context at the root of your application will cause an error: app/layout.tsx TypeScript JavaScriptTypeScript import { createContext } from 'react' // createContext is not supported in Server Components export const ThemeContext = createContext({}) export default function RootLayout({ children }) { return ( <html> <body> <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider> </body> </html> ) } To fix this, create your context and render its provider inside of a Client Component: app/theme-provider.tsx TypeScript JavaScriptTypeScript 'use client' import { createContext } from 'react' export const ThemeContext = createContext({}) export default function ThemeProvider({ children, }: { children: React.ReactNode }) { return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider> } Your Server Component will now be able to directly render your provider since it's been marked as a Client Component: app/layout.tsx TypeScript JavaScriptTypeScript import ThemeProvider from './theme-provider' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html> <body> <ThemeProvider>{children}</ThemeProvider> </body> </html> ) } With the provider rendered at the root, all other Client Components throughout your app will be able to consume this context. > **Good to know**: You should render providers as deep as possible in the tree – notice how `ThemeProvider` only wraps `{children}` instead of the entire `<html>` document. This makes it easier for Next.js to optimize the static parts of your Server Components. #### [Advice for Library Authors](#advice-for-library-authors) In a similar fashion, library authors creating packages to be consumed by other developers can use the `"use client"` directive to mark client entry points of their package. This allows users of the package to import package components directly into their Server Components without having to create a wrapping boundary. You can optimize your package by using ['use client' deeper in the tree](#moving-client-components-down-the-tree), allowing the imported modules to be part of the Server Component module graph. It's worth noting some bundlers might strip out `"use client"` directives. You can find an example of how to configure esbuild to include the `"use client"` directive in the [React Wrap Balancer](https://github.com/shuding/react-wrap-balancer/blob/main/tsup.config.ts#L10-L13) and [Vercel Analytics](https://github.com/vercel/analytics/blob/main/packages/web/tsup.config.js#L26-L30) repositories. [Client Components](#client-components) --------------------------------------- ### [Moving Client Components Down the Tree](#moving-client-components-down-the-tree) To reduce the Client JavaScript bundle size, we recommend moving Client Components down your component tree. For example, you may have a Layout that has static elements (e.g. logo, links, etc) and an interactive search bar that uses state. Instead of making the whole layout a Client Component, move the interactive logic to a Client Component (e.g. `<SearchBar />`) and keep your layout as a Server Component. This means you don't have to send all the component Javascript of the layout to the client. app/layout.tsx TypeScript JavaScriptTypeScript // SearchBar is a Client Component import SearchBar from './searchbar' // Logo is a Server Component import Logo from './logo' // Layout is a Server Component by default export default function Layout({ children }: { children: React.ReactNode }) { return ( <> <nav> <Logo /> <SearchBar /> </nav> <main>{children}</main> </> ) } ### [Passing props from Server to Client Components (Serialization)](#passing-props-from-server-to-client-components-serialization) If you fetch data in a Server Component, you may want to pass data down as props to Client Components. Props passed from the Server to Client Components need to be [serializable](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values) by React. If your Client Components depend on data that is not serializable, you can [fetch data on the client with a third party library](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-client-with-third-party-libraries) or on the server via a [Route Handler](/docs/app/building-your-application/routing/route-handlers). [Interleaving Server and Client Components](#interleaving-server-and-client-components) --------------------------------------------------------------------------------------- When interleaving Client and Server Components, it may be helpful to visualize your UI as a tree of components. Starting with the [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required), which is a Server Component, you can then render certain subtrees of components on the client by adding the `"use client"` directive. Within those client subtrees, you can still nest Server Components or call Server Actions, however there are some things to keep in mind: * During a request-response lifecycle, your code moves from the server to the client. If you need to access data or resources on the server while on the client, you'll be making a **new** request to the server - not switching back and forth. * When a new request is made to the server, all Server Components are rendered first, including those nested inside Client Components. The rendered result (RSC Payload) will contain references to the locations of Client Components. Then, on the client, React uses the RSC Payload to reconcile Server and Client Components into a single tree. * Since Client Components are rendered after Server Components, you cannot import a Server Component into a Client Component module (since it would require a new request back to the server). Instead, you can pass a Server Component as `props` to a Client Component. See the [unsupported pattern](#unsupported-pattern-importing-server-components-into-client-components) and [supported pattern](#supported-pattern-passing-server-components-to-client-components-as-props) sections below. ### [Unsupported Pattern: Importing Server Components into Client Components](#unsupported-pattern-importing-server-components-into-client-components) The following pattern is not supported. You cannot import a Server Component into a Client Component: app/client-component.tsx TypeScript JavaScriptTypeScript 'use client' // You cannot import a Server Component into a Client Component. import ServerComponent from './Server-Component' export default function ClientComponent({ children, }: { children: React.ReactNode }) { const [count, setCount] = useState(0) return ( <> <button onClick={() => setCount(count + 1)}>{count}</button> <ServerComponent /> </> ) } ### [Supported Pattern: Passing Server Components to Client Components as Props](#supported-pattern-passing-server-components-to-client-components-as-props) The following pattern is supported. You can pass Server Components as a prop to a Client Component. A common pattern is to use the React `children` prop to create a _"slot"_ in your Client Component. In the example below, `<ClientComponent>` accepts a `children` prop: app/client-component.tsx TypeScript JavaScriptTypeScript 'use client' import { useState } from 'react' export default function ClientComponent({ children, }: { children: React.ReactNode }) { const [count, setCount] = useState(0) return ( <> <button onClick={() => setCount(count + 1)}>{count}</button> {children} </> ) } `<ClientComponent>` doesn't know that `children` will eventually be filled in by the result of a Server Component. The only responsibility `<ClientComponent>` has is to decide **where** `children` will eventually be placed. In a parent Server Component, you can import both the `<ClientComponent>` and `<ServerComponent>` and pass `<ServerComponent>` as a child of `<ClientComponent>`: app/page.tsx TypeScript JavaScriptTypeScript // This pattern works: // You can pass a Server Component as a child or prop of a // Client Component. import ClientComponent from './client-component' import ServerComponent from './server-component' // Pages in Next.js are Server Components by default export default function Page() { return ( <ClientComponent> <ServerComponent /> </ClientComponent> ) } With this approach, `<ClientComponent>` and `<ServerComponent>` are decoupled and can be rendered independently. In this case, the child `<ServerComponent>` can be rendered on the server, well before `<ClientComponent>` is rendered on the client. > **Good to know:** > > * The pattern of "lifting content up" has been used to avoid re-rendering a nested child component when a parent component re-renders. > * You're not limited to the `children` prop. You can use any prop to pass JSX. [Previous Client Components ](/docs/app/building-your-application/rendering/client-components) [Next Edge and Node.js Runtimes ](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"3e86e5318c26abc911f1fce259d8bdf3\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [ generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [The metadata object](#the-metadata-object) * [generateMetadata function](#generatemetadata-function) * [Parameters](#parameters) * [Returns](#returns) * [Metadata Fields](#metadata-fields) * [title](#title) * [String](#string) * [Template object](#template-object) * [Default](#default) * [Template](#template) * [Absolute](#absolute) * [description](#description) * [Basic Fields](#basic-fields) * [metadataBase](#metadatabase) * [Default value](#default-value) * [URL Composition](#url-composition) * [openGraph](#opengraph) * [robots](#robots) * [icons](#icons) * [themeColor](#themecolor) * [manifest](#manifest) * [twitter](#twitter) * [viewport](#viewport) * [verification](#verification) * [appleWebApp](#applewebapp) * [alternates](#alternates) * [appLinks](#applinks) * [archives](#archives) * [assets](#assets) * [bookmarks](#bookmarks) * [category](#category) * [other](#other) * [Unsupported Metadata](#unsupported-metadata) * [Resource hints](#resource-hints) * [<link rel="preload">](#link-relpreload) * [<link rel="preconnect">](#link-relpreconnect) * [<link rel="dns-prefetch">](#link-reldns-prefetch) * [Types](#types) * [metadata object](#metadata-object) * [generateMetadata function](#generatemetadata-function-1) * [Regular function](#regular-function) * [Async function](#async-function) * [With segment props](#with-segment-props) * [With parent metadata](#with-parent-metadata) * [JavaScript Projects](#javascript-projects) * [Version History](#version-history) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/generate-metadata.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)generateMetadata Metadata Object and generateMetadata Options ============================================ This page covers all **Config-based Metadata** options with `generateMetadata` and the static metadata object. layout.tsx | page.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' // either Static metadata export const metadata: Metadata = { title: '...', } // or Dynamic metadata export async function generateMetadata({ params }) { return { title: '...', } } > **Good to know**: > > * The `metadata` object and `generateMetadata` function exports are **only supported in Server Components**. > * You cannot export both the `metadata` object and `generateMetadata` function from the same route segment. [The `metadata` object](#the-metadata-object) --------------------------------------------- To define static metadata, export a [`Metadata` object](#metadata-fields) from a `layout.js` or `page.js` file. layout.tsx | page.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { title: '...', description: '...', } export default function Page() {} See the [Metadata Fields](#metadata-fields) for a complete list of supported options. [`generateMetadata` function](#generatemetadata-function) --------------------------------------------------------- Dynamic metadata depends on **dynamic information**, such as the current route parameters, external data, or `metadata` in parent segments, can be set by exporting a `generateMetadata` function that returns a [`Metadata` object](#metadata-fields). app/products/\[id\]/page.tsx TypeScript JavaScriptTypeScript import { Metadata, ResolvingMetadata } from 'next' type Props = { params: { id: string } searchParams: { [key: string]: string | string[] | undefined } } export async function generateMetadata( { params, searchParams }: Props, parent: ResolvingMetadata ): Promise<Metadata> { // read route params const id = params.id // fetch data const product = await fetch(`https://.../${id}`).then((res) => res.json()) // optionally access and extend (rather than replace) parent metadata const previousImages = (await parent).openGraph?.images || [] return { title: product.title, openGraph: { images: ['/some-specific-page-image.jpg', ...previousImages], }, } } export default function Page({ params, searchParams }: Props) {} ### [Parameters](#parameters) `generateMetadata` function accepts the following parameters: * `props` - An object containing the parameters of the current route: * `params` - An object containing the [dynamic route parameters](/docs/app/building-your-application/routing/dynamic-routes) object from the root segment down to the segment `generateMetadata` is called from. Examples: Route URL `params` `app/shop/[slug]/page.js` `/shop/1` `{ slug: '1' }` `app/shop/[tag]/[item]/page.js` `/shop/1/2` `{ tag: '1', item: '2' }` `app/shop/[...slug]/page.js` `/shop/1/2` `{ slug: ['1', '2'] }` * `searchParams` - An object containing the current URL's [search params](https://developer.mozilla.org/docs/Learn/Common_questions/What_is_a_URL#parameters). Examples: URL `searchParams` `/shop?a=1` `{ a: '1' }` `/shop?a=1&b=2` `{ a: '1', b: '2' }` `/shop?a=1&a=2` `{ a: ['1', '2'] }` * `parent` - A promise of the resolved metadata from parent route segments. ### [Returns](#returns) `generateMetadata` should return a [`Metadata` object](#metadata-fields) containing one or more metadata fields. > **Good to know**: > > * If metadata doesn't depend on runtime information, it should be defined using the static [`metadata` object](#the-metadata-object) rather than `generateMetadata`. > * `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable. > * `searchParams` are only available in `page.js` segments. > * The [`redirect()`](/docs/app/api-reference/functions/redirect) and [`notFound()`](/docs/app/api-reference/functions/not-found) Next.js methods can also be used inside `generateMetadata`. [Metadata Fields](#metadata-fields) ----------------------------------- ### [`title`](#title) The `title` attribute is used to set the title of the document. It can be defined as a simple [string](#string) or an optional [template object](#template-object). #### [String](#string) layout.js | page.js export const metadata = { title: 'Next.js', } <head> output <title>Next.js</title> #### [Template object](#template-object) app/layout.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { title: { template: '...', default: '...', absolute: '...', }, } ##### [Default](#default) `title.default` can be used to provide a **fallback title** to child route segments that don't define a `title`. app/layout.tsx import type { Metadata } from 'next' export const metadata: Metadata = { title: { default: 'Acme', }, } app/about/page.tsx import type { Metadata } from 'next' export const metadata: Metadata = {} // Output: <title>Acme</title> ##### [Template](#template) `title.template` can be used to add a prefix or a suffix to `titles` defined in **child** route segments. app/layout.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { title: { template: '%s | Acme', default: 'Acme', // a default is required when creating a template }, } app/about/page.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { title: 'About', } // Output: <title>About | Acme</title> > **Good to know**: > > * `title.template` applies to **child** route segments and **not** the segment it's defined in. This means: > > * `title.default` is **required** when you add a `title.template`. > * `title.template` defined in `layout.js` will not apply to a `title` defined in a `page.js` of the same route segment. > * `title.template` defined in `page.js` has no effect because a page is always the terminating segment (it doesn't have any children route segments). > * `title.template` has **no effect** if a route has not defined a `title` or `title.default`. > ##### [Absolute](#absolute) `title.absolute` can be used to provide a title that **ignores** `title.template` set in parent segments. app/layout.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { title: { template: '%s | Acme', }, } app/about/page.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { title: { absolute: 'About', }, } // Output: <title>About</title> > **Good to know**: > > * `layout.js` > > * `title` (string) and `title.default` define the default title for child segments (that do not define their own `title`). It will augment `title.template` from the closest parent segment if it exists. > * `title.absolute` defines the default title for child segments. It ignores `title.template` from parent segments. > * `title.template` defines a new title template for child segments. > * `page.js` > > * If a page does not define its own title the closest parents resolved title will be used. > * `title` (string) defines the routes title. It will augment `title.template` from the closest parent segment if it exists. > * `title.absolute` defines the route title. It ignores `title.template` from parent segments. > * `title.template` has no effect in `page.js` because a page is always the terminating segment of a route. ### [`description`](#description) layout.js | page.js export const metadata = { description: 'The React Framework for the Web', } <head> output <meta name="description" content="The React Framework for the Web" /> ### [Basic Fields](#basic-fields) layout.js | page.js export const metadata = { generator: 'Next.js', applicationName: 'Next.js', referrer: 'origin-when-cross-origin', keywords: ['Next.js', 'React', 'JavaScript'], authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://nextjs.org' }], creator: 'Jiachi Liu', publisher: 'Sebastian Markbåge', formatDetection: { email: false, address: false, telephone: false, }, } <head> output <meta name="application-name" content="Next.js" /> <meta name="author" content="Seb" /> <link rel="author" href="https://nextjs.org" /> <meta name="author" content="Josh" /> <meta name="generator" content="Next.js" /> <meta name="keywords" content="Next.js,React,JavaScript" /> <meta name="referrer" content="origin-when-cross-origin" /> <meta name="color-scheme" content="dark" /> <meta name="creator" content="Jiachi Liu" /> <meta name="publisher" content="Sebastian Markbåge" /> <meta name="format-detection" content="telephone=no, address=no, email=no" /> ### [`metadataBase`](#metadatabase) `metadataBase` is a convenience option to set a base URL prefix for `metadata` fields that require a fully qualified URL. * `metadataBase` allows URL-based `metadata` fields defined in the **current route segment and below** to use a **relative path** instead of an otherwise required absolute URL. * The field's relative path will be composed with `metadataBase` to form a fully qualified URL. * If not configured, `metadataBase` is **automatically populated** with a [default value](#default-value). layout.js | page.js export const metadata = { metadataBase: new URL('https://acme.com'), alternates: { canonical: '/', languages: { 'en-US': '/en-US', 'de-DE': '/de-DE', }, }, openGraph: { images: '/og-image.png', }, } <head> output <link rel="canonical" href="https://acme.com" /> <link rel="alternate" hreflang="en-US" href="https://acme.com/en-US" /> <link rel="alternate" hreflang="de-DE" href="https://acme.com/de-DE" /> <meta property="og:image" content="https://acme.com/og-image.png" /> > **Good to know**: > > * `metadataBase` is typically set in root `app/layout.js` to apply to URL-based `metadata` fields across all routes. > * All URL-based `metadata` fields that require absolute URLs can be configured with a `metadataBase` option. > * `metadataBase` can contain a subdomain e.g. `https://app.acme.com` or base path e.g. `https://acme.com/start/from/here` > * If a `metadata` field provides an absolute URL, `metadataBase` will be ignored. > * Using a relative path in a URL-based `metadata` field without configuring a `metadataBase` will cause a build error. > * Next.js will normalize duplicate slashes between `metadataBase` (e.g. `https://acme.com/`) and a relative field (e.g. `/path`) to a single slash (e.g. `https://acme.com/path`) #### [Default value](#default-value) If not configured, `metadataBase` has a **default value** * When [`VERCEL_URL`](https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#:~:text=.-,VERCEL_URL,-The%20domain%20name) is detected: `https://${process.env.VERCEL_URL}` otherwise it falls back to `http://localhost:${process.env.PORT || 3000}`. * When overriding the default, we recommend using environment variables to compute the URL. This allows configuring a URL for local development, staging, and production environments. #### [URL Composition](#url-composition) URL composition favors developer intent over default directory traversal semantics. * Trailing slashes between `metadataBase` and `metadata` fields are normalized. * An "absolute" path in a `metadata` field (that typically would replace the whole URL path) is treated as a "relative" path (starting from the end of `metadataBase`). For example, given the following `metadataBase`: app/layout.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { metadataBase: new URL('https://acme.com'), } Any `metadata` fields that inherit the above `metadataBase` and set their own value will be resolved as follows: `metadata` field Resolved URL `/` `https://acme.com` `./` `https://acme.com` `payments` `https://acme.com/payments` `/payments` `https://acme.com/payments` `./payments` `https://acme.com/payments` `../payments` `https://acme.com/payments` `https://beta.acme.com/payments` `https://beta.acme.com/payments` ### [`openGraph`](#opengraph) layout.js | page.js export const metadata = { openGraph: { title: 'Next.js', description: 'The React Framework for the Web', url: 'https://nextjs.org', siteName: 'Next.js', images: [ { url: 'https://nextjs.org/og.png', // Must be an absolute URL width: 800, height: 600, }, { url: 'https://nextjs.org/og-alt.png', // Must be an absolute URL width: 1800, height: 1600, alt: 'My custom alt', }, ], locale: 'en_US', type: 'website', }, } <head> output <meta property="og:title" content="Next.js" /> <meta property="og:description" content="The React Framework for the Web" /> <meta property="og:url" content="https://nextjs.org/" /> <meta property="og:site_name" content="Next.js" /> <meta property="og:locale" content="en_US" /> <meta property="og:image:url" content="https://nextjs.org/og.png" /> <meta property="og:image:width" content="800" /> <meta property="og:image:height" content="600" /> <meta property="og:image:url" content="https://nextjs.org/og-alt.png" /> <meta property="og:image:width" content="1800" /> <meta property="og:image:height" content="1600" /> <meta property="og:image:alt" content="My custom alt" /> <meta property="og:type" content="website" /> layout.js | page.js export const metadata = { openGraph: { title: 'Next.js', description: 'The React Framework for the Web', type: 'article', publishedTime: '2023-01-01T00:00:00.000Z', authors: ['Seb', 'Josh'], }, } <head> output <meta property="og:title" content="Next.js" /> <meta property="og:description" content="The React Framework for the Web" /> <meta property="og:type" content="article" /> <meta property="article:published_time" content="2023-01-01T00:00:00.000Z" /> <meta property="article:author" content="Seb" /> <meta property="article:author" content="Josh" /> > **Good to know**: > > * It may be more convenient to use the [file-based Metadata API](/docs/app/api-reference/file-conventions/metadata/opengraph-image#image-files-jpg-png-gif) for Open Graph images. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you. ### [`robots`](#robots) import type { Metadata } from 'next' export const metadata: Metadata = { robots: { index: false, follow: true, nocache: true, googleBot: { index: true, follow: false, noimageindex: true, 'max-video-preview': -1, 'max-image-preview': 'large', 'max-snippet': -1, }, }, } <head> output <meta name="robots" content="noindex, follow, nocache" /> <meta name="googlebot" content="index, nofollow, noimageindex, max-video-preview:-1, max-image-preview:large, max-snippet:-1" /> ### [`icons`](#icons) > **Good to know**: We recommend using the [file-based Metadata API](/docs/app/api-reference/file-conventions/metadata/app-icons#image-files-ico-jpg-png) for icons where possible. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you. layout.js | page.js export const metadata = { icons: { icon: '/icon.png', shortcut: '/shortcut-icon.png', apple: '/apple-icon.png', other: { rel: 'apple-touch-icon-precomposed', url: '/apple-touch-icon-precomposed.png', }, }, } <head> output <link rel="shortcut icon" href="/shortcut-icon.png" /> <link rel="icon" href="/icon.png" /> <link rel="apple-touch-icon" href="/apple-icon.png" /> <link rel="apple-touch-icon-precomposed" href="/apple-touch-icon-precomposed.png" /> layout.js | page.js export const metadata = { icons: { icon: [ { url: '/icon.png' }, new URL('/icon.png', 'https://example.com'), { url: '/icon-dark.png', media: '(prefers-color-scheme: dark)' }, ], shortcut: ['/shortcut-icon.png'], apple: [ { url: '/apple-icon.png' }, { url: '/apple-icon-x3.png', sizes: '180x180', type: 'image/png' }, ], other: [ { rel: 'apple-touch-icon-precomposed', url: '/apple-touch-icon-precomposed.png', }, ], }, } <head> output <link rel="shortcut icon" href="/shortcut-icon.png" /> <link rel="icon" href="/icon.png" /> <link rel="icon" href="https://example.com/icon.png" /> <link rel="icon" href="/icon-dark.png" media="(prefers-color-scheme: dark)" /> <link rel="apple-touch-icon" href="/apple-icon.png" /> <link rel="apple-touch-icon-precomposed" href="/apple-touch-icon-precomposed.png" /> <link rel="apple-touch-icon" href="/apple-icon-x3.png" sizes="180x180" type="image/png" /> > **Good to know**: The `msapplication-*` meta tags are no longer supported in Chromium builds of Microsoft Edge, and thus no longer needed. ### [`themeColor`](#themecolor) > **Deprecated**: The `themeColor` option in `metadata` is deprecated as of Next.js 14. Please use the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport) instead. ### [`manifest`](#manifest) A web application manifest, as defined in the [Web Application Manifest specification](https://developer.mozilla.org/docs/Web/Manifest). layout.js | page.js export const metadata = { manifest: 'https://nextjs.org/manifest.json', } <head> output <link rel="manifest" href="https://nextjs.org/manifest.json" /> ### [`twitter`](#twitter) The Twitter specification is (surprisingly) used for more than just X (formerly known as Twitter). Learn more about the [Twitter Card markup reference](https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/markup). layout.js | page.js export const metadata = { twitter: { card: 'summary_large_image', title: 'Next.js', description: 'The React Framework for the Web', siteId: '1467726470533754880', creator: '@nextjs', creatorId: '1467726470533754880', images: ['https://nextjs.org/og.png'], // Must be an absolute URL }, } <head> output <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site:id" content="1467726470533754880" /> <meta name="twitter:creator" content="@nextjs" /> <meta name="twitter:creator:id" content="1467726470533754880" /> <meta name="twitter:title" content="Next.js" /> <meta name="twitter:description" content="The React Framework for the Web" /> <meta name="twitter:image" content="https://nextjs.org/og.png" /> layout.js | page.js export const metadata = { twitter: { card: 'app', title: 'Next.js', description: 'The React Framework for the Web', siteId: '1467726470533754880', creator: '@nextjs', creatorId: '1467726470533754880', images: { url: 'https://nextjs.org/og.png', alt: 'Next.js Logo', }, app: { name: 'twitter_app', id: { iphone: 'twitter_app://iphone', ipad: 'twitter_app://ipad', googleplay: 'twitter_app://googleplay', }, url: { iphone: 'https://iphone_url', ipad: 'https://ipad_url', }, }, }, } <head> output <meta name="twitter:site:id" content="1467726470533754880" /> <meta name="twitter:creator" content="@nextjs" /> <meta name="twitter:creator:id" content="1467726470533754880" /> <meta name="twitter:title" content="Next.js" /> <meta name="twitter:description" content="The React Framework for the Web" /> <meta name="twitter:card" content="app" /> <meta name="twitter:image" content="https://nextjs.org/og.png" /> <meta name="twitter:image:alt" content="Next.js Logo" /> <meta name="twitter:app:name:iphone" content="twitter_app" /> <meta name="twitter:app:id:iphone" content="twitter_app://iphone" /> <meta name="twitter:app:id:ipad" content="twitter_app://ipad" /> <meta name="twitter:app:id:googleplay" content="twitter_app://googleplay" /> <meta name="twitter:app:url:iphone" content="https://iphone_url" /> <meta name="twitter:app:url:ipad" content="https://ipad_url" /> <meta name="twitter:app:name:ipad" content="twitter_app" /> <meta name="twitter:app:name:googleplay" content="twitter_app" /> ### [`viewport`](#viewport) > **Deprecated**: The `viewport` option in `metadata` is deprecated as of Next.js 14. Please use the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport) instead. ### [`verification`](#verification) layout.js | page.js export const metadata = { verification: { google: 'google', yandex: 'yandex', yahoo: 'yahoo', other: { me: ['my-email', 'my-link'], }, }, } <head> output <meta name="google-site-verification" content="google" /> <meta name="y_key" content="yahoo" /> <meta name="yandex-verification" content="yandex" /> <meta name="me" content="my-email" /> <meta name="me" content="my-link" /> ### [`appleWebApp`](#applewebapp) layout.js | page.js export const metadata = { itunes: { appId: 'myAppStoreID', appArgument: 'myAppArgument', }, appleWebApp: { title: 'Apple Web App', statusBarStyle: 'black-translucent', startupImage: [ '/assets/startup/apple-touch-startup-image-768x1004.png', { url: '/assets/startup/apple-touch-startup-image-1536x2008.png', media: '(device-width: 768px) and (device-height: 1024px)', }, ], }, } <head> output <meta name="apple-itunes-app" content="app-id=myAppStoreID, app-argument=myAppArgument" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-title" content="Apple Web App" /> <link href="/assets/startup/apple-touch-startup-image-768x1004.png" rel="apple-touch-startup-image" /> <link href="/assets/startup/apple-touch-startup-image-1536x2008.png" media="(device-width: 768px) and (device-height: 1024px)" rel="apple-touch-startup-image" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> ### [`alternates`](#alternates) layout.js | page.js export const metadata = { alternates: { canonical: 'https://nextjs.org', languages: { 'en-US': 'https://nextjs.org/en-US', 'de-DE': 'https://nextjs.org/de-DE', }, media: { 'only screen and (max-width: 600px)': 'https://nextjs.org/mobile', }, types: { 'application/rss+xml': 'https://nextjs.org/rss', }, }, } <head> output <link rel="canonical" href="https://nextjs.org" /> <link rel="alternate" hreflang="en-US" href="https://nextjs.org/en-US" /> <link rel="alternate" hreflang="de-DE" href="https://nextjs.org/de-DE" /> <link rel="alternate" media="only screen and (max-width: 600px)" href="https://nextjs.org/mobile" /> <link rel="alternate" type="application/rss+xml" href="https://nextjs.org/rss" /> ### [`appLinks`](#applinks) layout.js | page.js export const metadata = { appLinks: { ios: { url: 'https://nextjs.org/ios', app_store_id: 'app_store_id', }, android: { package: 'com.example.android/package', app_name: 'app_name_android', }, web: { url: 'https://nextjs.org/web', should_fallback: true, }, }, } <head> output <meta property="al:ios:url" content="https://nextjs.org/ios" /> <meta property="al:ios:app_store_id" content="app_store_id" /> <meta property="al:android:package" content="com.example.android/package" /> <meta property="al:android:app_name" content="app_name_android" /> <meta property="al:web:url" content="https://nextjs.org/web" /> <meta property="al:web:should_fallback" content="true" /> ### [`archives`](#archives) Describes a collection of records, documents, or other materials of historical interest ([source](https://www.w3.org/TR/2011/WD-html5-20110113/links.html#rel-archives)). layout.js | page.js export const metadata = { archives: ['https://nextjs.org/13'], } <head> output <link rel="archives" href="https://nextjs.org/13" /> ### [`assets`](#assets) layout.js | page.js export const metadata = { assets: ['https://nextjs.org/assets'], } <head> output <link rel="assets" href="https://nextjs.org/assets" /> ### [`bookmarks`](#bookmarks) layout.js | page.js export const metadata = { bookmarks: ['https://nextjs.org/13'], } <head> output <link rel="bookmarks" href="https://nextjs.org/13" /> ### [`category`](#category) layout.js | page.js export const metadata = { category: 'technology', } <head> output <meta name="category" content="technology" /> ### [`other`](#other) All metadata options should be covered using the built-in support. However, there may be custom metadata tags specific to your site, or brand new metadata tags just released. You can use the `other` option to render any custom metadata tag. layout.js | page.js export const metadata = { other: { custom: 'meta', }, } <head> output <meta name="custom" content="meta" /> If you want to generate multiple same key meta tags you can use array value. layout.js | page.js export const metadata = { other: { custom: ['meta1', 'meta2'], }, } <head> output <meta name="custom" content="meta1" /> <meta name="custom" content="meta2" /> [Unsupported Metadata](#unsupported-metadata) --------------------------------------------- The following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself. Metadata Recommendation `<meta http-equiv="...">` Use appropriate HTTP Headers via [`redirect()`](/docs/app/api-reference/functions/redirect), [Middleware](/docs/app/building-your-application/routing/middleware#nextresponse), [Security Headers](/docs/app/api-reference/next-config-js/headers) `<base>` Render the tag in the layout or page itself. `<noscript>` Render the tag in the layout or page itself. `<style>` Learn more about [styling in Next.js](/docs/app/building-your-application/styling/css-modules). `<script>` Learn more about [using scripts](/docs/app/building-your-application/optimizing/scripts). `<link rel="stylesheet" />` `import` stylesheets directly in the layout or page itself. `<link rel="preload />` Use [ReactDOM preload method](#link-relpreload) `<link rel="preconnect" />` Use [ReactDOM preconnect method](#link-relpreconnect) `<link rel="dns-prefetch" />` Use [ReactDOM prefetchDNS method](#link-reldns-prefetch) ### [Resource hints](#resource-hints) The `<link>` element has a number of `rel` keywords that can be used to hint to the browser that an external resource is likely to be needed. The browser uses this information to apply preloading optimizations depending on the keyword. While the Metadata API doesn't directly support these hints, you can use new [`ReactDOM` methods](https://github.com/facebook/react/pull/26237) to safely insert them into the `<head>` of the document. app/preload-resources.tsx TypeScript JavaScriptTypeScript 'use client' import ReactDOM from 'react-dom' export function PreloadResources() { ReactDOM.preload('...', { as: '...' }) ReactDOM.preconnect('...', { crossOrigin: '...' }) ReactDOM.prefetchDNS('...') return null } ##### [`<link rel="preload">`](#link-relpreload) Start loading a resource early in the page rendering (browser) lifecycle. [MDN Docs](https://developer.mozilla.org/docs/Web/HTML/Attributes/rel/preload). ReactDOM.preload(href: string, options: { as: string }) <head> output <link rel="preload" href="..." as="..." /> ##### [`<link rel="preconnect">`](#link-relpreconnect) Preemptively initiate a connection to an origin. [MDN Docs](https://developer.mozilla.org/docs/Web/HTML/Attributes/rel/preconnect). ReactDOM.preconnect(href: string, options?: { crossOrigin?: string }) <head> output <link rel="preconnect" href="..." crossorigin /> ##### [`<link rel="dns-prefetch">`](#link-reldns-prefetch) Attempt to resolve a domain name before resources get requested. [MDN Docs](https://developer.mozilla.org/docs/Web/HTML/Attributes/rel/dns-prefetch). ReactDOM.prefetchDNS(href: string) <head> output <link rel="dns-prefetch" href="..." /> > **Good to know**: > > * These methods are currently only supported in Client Components, which are still Server Side Rendered on initial page load. > * Next.js in-built features such as `next/font`, `next/image` and `next/script` automatically handle relevant resource hints. > * React 18.3 does not yet include type definitions for `ReactDOM.preload`, `ReactDOM.preconnect`, and `ReactDOM.preconnectDNS`. You can use `// @ts-ignore` as a temporary solution to avoid type errors. [Types](#types) --------------- You can add type safety to your metadata by using the `Metadata` type. If you are using the [built-in TypeScript plugin](/docs/app/building-your-application/configuring/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want. ### [`metadata` object](#metadata-object) import type { Metadata } from 'next' export const metadata: Metadata = { title: 'Next.js', } ### [`generateMetadata` function](#generatemetadata-function-1) #### [Regular function](#regular-function) import type { Metadata } from 'next' export function generateMetadata(): Metadata { return { title: 'Next.js', } } #### [Async function](#async-function) import type { Metadata } from 'next' export async function generateMetadata(): Promise<Metadata> { return { title: 'Next.js', } } #### [With segment props](#with-segment-props) import type { Metadata } from 'next' type Props = { params: { id: string } searchParams: { [key: string]: string | string[] | undefined } } export function generateMetadata({ params, searchParams }: Props): Metadata { return { title: 'Next.js', } } export default function Page({ params, searchParams }: Props) {} #### [With parent metadata](#with-parent-metadata) import type { Metadata, ResolvingMetadata } from 'next' export async function generateMetadata( { params, searchParams }: Props, parent: ResolvingMetadata ): Promise<Metadata> { return { title: 'Next.js', } } #### [JavaScript Projects](#javascript-projects) For JavaScript projects, you can use JSDoc to add type safety. /** @type {import("next").Metadata} */ export const metadata = { title: 'Next.js', } [Version History](#version-history) ----------------------------------- Version Changes `v13.2.0` `viewport`, `themeColor`, and `colorScheme` deprecated in favor of the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport). `v13.2.0` `metadata` and `generateMetadata` introduced. Next Steps ---------- View all the Metadata API options. [ App Router ... File Conventions ### Metadata Files API documentation for the metadata file conventions. ](/docs/app/api-reference/file-conventions/metadata)[ App Router ... Functions ### generateViewport API Reference for the generateViewport function. ](/docs/app/api-reference/functions/generate-viewport)[ App Router ... Optimizing ### Metadata Use the Metadata API to define metadata in any layout or page. ](/docs/app/building-your-application/optimizing/metadata) [Previous generateImageMetadata ](/docs/app/api-reference/functions/generate-image-metadata) [Next generateSitemaps ](/docs/app/api-reference/functions/generate-sitemaps) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"af01124e2dc845466a7d9d8e0b1b8163\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/upgrading/from-vite
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [ Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Why Switch?](#why-switch) * [Slow initial page loading time](#slow-initial-page-loading-time) * [No automatic code splitting](#no-automatic-code-splitting) * [Network waterfalls](#network-waterfalls) * [Fast and intentional loading states](#fast-and-intentional-loading-states) * [Choose the data fetching strategy](#choose-the-data-fetching-strategy) * [Middleware](#middleware) * [Built-in Optimizations](#built-in-optimizations) * [Migration Steps](#migration-steps) * [Step 1: Install the Next.js Dependency](#step-1-install-the-nextjs-dependency) * [Step 2: Create the Next.js Configuration File](#step-2-create-the-nextjs-configuration-file) * [Step 3: Update TypeScript Configuration](#step-3-update-typescript-configuration) * [Step 4: Create the Root Layout](#step-4-create-the-root-layout) * [Step 5: Create the Entrypoint Page](#step-5-create-the-entrypoint-page) * [Step 6: Update Static Image Imports](#step-6-update-static-image-imports) * [Step 7: Migrate the Environment Variables](#step-7-migrate-the-environment-variables) * [Step 8: Update Scripts in package.json](#step-8-update-scripts-in-packagejson) * [Step 9: Clean Up](#step-9-clean-up) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/11-upgrading/04-from-vite.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Upgrading](/docs/app/building-your-application/upgrading)Migrating from Vite Migrating from Vite =================== This guide will help you migrate an existing Vite application to Next.js. [Why Switch?](#why-switch) -------------------------- There are several reasons why you might want to switch from Vite to Next.js: ### [Slow initial page loading time](#slow-initial-page-loading-time) If you have built your application with the [default Vite plugin for React](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react), your application is a purely client-side application. Client-side only applications, also known as single-page applications (SPAs), often experience slow initial page loading time. This happens due to a couple of reasons: 1. The browser needs to wait for the React code and your entire application bundle to download and run before your code is able to send requests to load some data. 2. Your application code grows with every new feature and extra dependency you add. ### [No automatic code splitting](#no-automatic-code-splitting) The previous issue of slow loading times can be somewhat managed with code splitting. However, if you try to do code splitting manually, you'll often make performance worse. It's easy to inadvertently introduce network waterfalls when code-splitting manually. Next.js provides automatic code splitting built into its router. ### [Network waterfalls](#network-waterfalls) A common cause of poor performance occurs when applications make sequential client-server requests to fetch data. One common pattern for data fetching in an SPA is to initially render a placeholder, and then fetch data after the component has mounted. Unfortunately, this means that a child component that fetches data can't start fetching until the parent component has finished loading its own data. While fetching data on the client is supported with Next.js, it also gives you the option to shift data fetching to the server, which can eliminate client-server waterfalls. ### [Fast and intentional loading states](#fast-and-intentional-loading-states) With built-in support for [streaming through React Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense), you can be more intentional about which parts of your UI you want to load first and in what order without introducing network waterfalls. This enables you to build pages that are faster to load and eliminate [layout shifts](https://vercel.com/blog/how-core-web-vitals-affect-seo). ### [Choose the data fetching strategy](#choose-the-data-fetching-strategy) Depending on your needs, Next.js allows you to choose your data fetching strategy on a page and component basis. You can decide to fetch at build time, at request time on the server, or on the client. For example, you can fetch data from your CMS and render your blog posts at build time, which can then be efficiently cached on a CDN. ### [Middleware](#middleware) [Next.js Middleware](/docs/app/building-your-application/routing/middleware) allows you to run code on the server before a request is completed. This is especially useful to avoid having a flash of unauthenticated content when the user visits an authenticated-only page by redirecting the user to a login page. The middleware is also useful for experimentation and [internationalization](/docs/app/building-your-application/routing/internationalization). ### [Built-in Optimizations](#built-in-optimizations) [Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/building-your-application/optimizing/scripts) often have significant impact on an application's performance. Next.js comes with built-in components that automatically optimize those for you. [Migration Steps](#migration-steps) ----------------------------------- Our goal with this migration is to get a working Next.js application as quickly as possible, so that you can then adopt Next.js features incrementally. To begin with, we'll keep it as a purely client-side application (SPA) without migrating your existing router. This helps minimize the chances of encountering issues during the migration process and reduces merge conflicts. ### [Step 1: Install the Next.js Dependency](#step-1-install-the-nextjs-dependency) The first thing you need to do is to install `next` as a dependency: Terminal npm install next@latest ### [Step 2: Create the Next.js Configuration File](#step-2-create-the-nextjs-configuration-file) Create a `next.config.mjs` at the root of your project. This file will hold your [Next.js configuration options](/docs/app/api-reference/next-config-js). next.config.mjs /** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // Outputs a Single-Page Application (SPA). distDir: './dist', // Changes the build output directory to `./dist/`. } export default nextConfig > **Good to know:** You can use either `.js` or `.mjs` for your Next.js configuration file. ### [Step 3: Update TypeScript Configuration](#step-3-update-typescript-configuration) If you're using TypeScript, you need to update your `tsconfig.json` file with the following changes to make it compatible with Next.js. If you're not using TypeScript, you can skip this step. 1. Remove the [project reference](https://www.typescriptlang.org/tsconfig#references) to `tsconfig.node.json` 2. Add `./dist/types/**/*.ts` and `./next-env.d.ts` to the [`include` array](https://www.typescriptlang.org/tsconfig#include) 3. Add `./node_modules` to the [`exclude` array](https://www.typescriptlang.org/tsconfig#exclude) 4. Add `{ "name": "next" }` to the [`plugins` array in `compilerOptions`](https://www.typescriptlang.org/tsconfig#plugins): `"plugins": [{ "name": "next" }]` 5. Set [`esModuleInterop`](https://www.typescriptlang.org/tsconfig#esModuleInterop) to `true`: `"esModuleInterop": true` 6. Set [`jsx`](https://www.typescriptlang.org/tsconfig#jsx) to `preserve`: `"jsx": "preserve"` 7. Set [`allowJs`](https://www.typescriptlang.org/tsconfig#allowJs) to `true`: `"allowJs": true` 8. Set [`forceConsistentCasingInFileNames`](https://www.typescriptlang.org/tsconfig#forceConsistentCasingInFileNames) to `true`: `"forceConsistentCasingInFileNames": true` 9. Set [`incremental`](https://www.typescriptlang.org/tsconfig#incremental) to `true`: `"incremental": true` Here's an example of a working `tsconfig.json` with those changes: tsconfig.json { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "esModuleInterop": true, "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "preserve", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "allowJs": true, "forceConsistentCasingInFileNames": true, "incremental": true, "plugins": [{ "name": "next" }] }, "include": ["./src", "./dist/types/**/*.ts", "./next-env.d.ts"], "exclude": ["./node_modules"] } You can find more information about configuring TypeScript on the [Next.js docs](/docs/app/building-your-application/configuring/typescript#typescript-plugin). ### [Step 4: Create the Root Layout](#step-4-create-the-root-layout) A Next.js [App Router](/docs/app) application must include a [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) file, which is a [React Server Component](/docs/app/building-your-application/rendering/server-components) that will wrap all pages in your application. This file is defined at the top level of the `app` directory. The closest equivalent to the root layout file in a Vite application is the [`index.html` file](https://vitejs.dev/guide/#index-html-and-project-root), which contains your `<html>`, `<head>`, and `<body>` tags. In this step, you'll convert your `index.html` file into a root layout file: 1. Create a new `app` directory in your `src` directory. 2. Create a new `layout.tsx` file inside that `app` directory: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return null } > **Good to know**: `.js`, `.jsx`, or `.tsx` extensions can be used for Layout files. 3. Copy the content of your `index.html` file into the previously created `<RootLayout>` component while replacing the `body.div#root` and `body.script` tags with `<div id="root">{children}</div>`: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/icon.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>My App</title> <meta name="description" content="My App is a..." /> </head> <body> <div id="root">{children}</div> </body> </html> ) } 4. Next.js already includes by default the [meta charset](https://developer.mozilla.org/docs/Web/HTML/Element/meta#charset) and [meta viewport](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag) tags, so you can safely remove those from your `<head>`: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <head> <link rel="icon" type="image/svg+xml" href="/icon.svg" /> <title>My App</title> <meta name="description" content="My App is a..." /> </head> <body> <div id="root">{children}</div> </body> </html> ) } 5. Any [metadata files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) such as `favicon.ico`, `icon.png`, `robots.txt` are automatically added to the application `<head>` tag as long as you have them placed into the top level of the `app` directory. After moving [all supported files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) into the `app` directory you can safely delete their `<link>` tags: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <head> <title>My App</title> <meta name="description" content="My App is a..." /> </head> <body> <div id="root">{children}</div> </body> </html> ) } 6. Finally, Next.js can manage your last `<head>` tags with the [Metadata API](/docs/app/building-your-application/optimizing/metadata). Move your final metadata info into an exported [`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object): app/layout.tsx TypeScript JavaScriptTypeScript import type { Metadata } from 'next' export const metadata: Metadata = { title: 'My App', description: 'My App is a...', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <div id="root">{children}</div> </body> </html> ) } With the above changes, you shifted from declaring everything in your `index.html` to using Next.js' convention-based approach built into the framework ([Metadata API](/docs/app/building-your-application/optimizing/metadata)). This approach enables you to more easily improve your SEO and web shareability of your pages. ### [Step 5: Create the Entrypoint Page](#step-5-create-the-entrypoint-page) On Next.js you declare an entrypoint for your application by creating a `page.tsx` file. The closest equivalent of this file on Vite is your `main.tsx` file. In this step, you’ll set up the entrypoint of your application. 1. **Create a `[[...slug]]` directory in your `app` directory.** Since in this guide we're aiming first to set up our Next.js as an SPA (Single Page Application), you need your page entrypoint to catch all possible routes of your application. For that, create a new `[[...slug]]` directory in your `app` directory. This directory is what is called an [optional catch-all route segment](/docs/app/building-your-application/routing/dynamic-routes#optional-catch-all-segments). Next.js uses a file-system based router where [directories are used to define routes](/docs/app/building-your-application/routing/defining-routes#creating-routes). This special directory will make sure that all routes of your application will be directed to its containing `page.tsx` file. 2. **Create a new `page.tsx` file inside the `app/[[...slug]]` directory with the following content:** app/\[\[...slug\]\]/page.tsx TypeScript JavaScriptTypeScript import '../../index.css' export function generateStaticParams() { return [{ slug: [''] }] } export default function Page() { return '...' // We'll update this } > **Good to know**: `.js`, `.jsx`, or `.tsx` extensions can be used for Page files. This file is a [Server Component](/docs/app/building-your-application/rendering/server-components). When you run `next build`, the file is prerendered into a static asset. It does _not_ require any dynamic code. This file imports our global CSS and tells [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) we are only going to generate one route, the index route at `/`. Now, let's move the rest of our Vite application which will run client-only. app/\[\[...slug\]\]/client.tsx TypeScript JavaScriptTypeScript 'use client' import React from 'react' import dynamic from 'next/dynamic' const App = dynamic(() => import('../../App'), { ssr: false }) export function ClientOnly() { return <App /> } This file is a [Client Component](/docs/app/building-your-application/rendering/client-components), defined by the `'use client'` directive. Client Components are still [prerendered to HTML](/docs/app/building-your-application/rendering/client-components#how-are-client-components-rendered) on the server before being sent to the client. Since we want a client-only application to start, we can configure Next.js to disable prerendering from the `App` component down. const App = dynamic(() => import('../../App'), { ssr: false }) Now, update your entrypoint page to use the new component: app/\[\[...slug\]\]/page.tsx TypeScript JavaScriptTypeScript import '../../index.css' import { ClientOnly } from './client' export function generateStaticParams() { return [{ slug: [''] }] } export default function Page() { return <ClientOnly /> } ### [Step 6: Update Static Image Imports](#step-6-update-static-image-imports) Next.js handles static image imports slightly different from Vite. With Vite, importing an image file will return its public URL as a string: App.tsx import image from './img.png' // `image` will be '/assets/img.2d8efhg.png' in production export default function App() { return <img src={image} /> } With Next.js, static image imports return an object. The object can then be used directly with the Next.js [`<Image>` component](/docs/app/api-reference/components/image), or you can use the object's `src` property with your existing `<img>` tag. The `<Image>` component has the added benefits of [automatic image optimization](/docs/app/building-your-application/optimizing/images). The `<Image>` component automatically sets the `width` and `height` attributes of the resulting `<img>` based on the image's dimensions. This prevents layout shifts when the image loads. However, this can cause issues if your app contains images with only one of their dimensions being styled without the other styled to `auto`. When not styled to `auto`, the dimension will default to the `<img>` dimension attribute's value, which can cause the image to appear distorted. Keeping the `<img>` tag will reduce the amount of changes in your application and prevent the above issues. You can then optionally later migrate to the `<Image>` component to take advantage of optimizing images by [configuring a loader](/docs/app/building-your-application/optimizing/images#loaders), or moving to the default Next.js server which has automatic image optimization. 1. **Convert absolute import paths for images imported from `/public` into relative imports:** // Before import logo from '/logo.png' // After import logo from '../public/logo.png' 2. **Pass the image `src` property instead of the whole image object to your `<img>` tag:** // Before <img src={logo} /> // After <img src={logo.src} /> Alternatively, you can reference the public URL for the image asset based on the filename. For example, `public/logo.png` will serve the image at `/logo.png` for your application, which would be the `src` value. > **Warning:** If you're using TypeScript, you might encounter type errors when accessing the `src` property. You can safely ignore those for now. They will be fixed by the end of this guide. ### [Step 7: Migrate the Environment Variables](#step-7-migrate-the-environment-variables) Next.js has support for `.env` [environment variables](/docs/app/building-your-application/configuring/environment-variables) similar to Vite. The main difference is the prefix used to expose environment variables on the client-side. * Change all environment variables with the `VITE_` prefix to `NEXT_PUBLIC_`. Vite exposes a few built-in environment variables on the special `import.meta.env` object which aren’t supported by Next.js. You need to update their usage as follows: * `import.meta.env.MODE` ⇒ `process.env.NODE_ENV` * `import.meta.env.PROD` ⇒ `process.env.NODE_ENV === 'production'` * `import.meta.env.DEV` ⇒ `process.env.NODE_ENV !== 'production'` * `import.meta.env.SSR` ⇒ `typeof window !== 'undefined'` Next.js also doesn't provide a built-in `BASE_URL` environment variable. However, you can still configure one, if you need it: 1. **Add the following to your `.env` file:** .env # ... NEXT_PUBLIC_BASE_PATH="/some-base-path" 2. **Set [`basePath`](/docs/app/api-reference/next-config-js/basePath) to `process.env.NEXT_PUBLIC_BASE_PATH` in your `next.config.mjs` file:** next.config.mjs /** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // Outputs a Single-Page Application (SPA). distDir: './dist', // Changes the build output directory to `./dist/`. basePath: process.env.NEXT_PUBLIC_BASE_PATH, // Sets the base path to `/some-base-path`. } export default nextConfig 3. **Update `import.meta.env.BASE_URL` usages to `process.env.NEXT_PUBLIC_BASE_PATH`** ### [Step 8: Update Scripts in `package.json`](#step-8-update-scripts-in-packagejson) You should now be able to run your application to test if you successfully migrated to Next.js. But before that, you need to update your `scripts` in your `package.json` with Next.js related commands, and add `.next` and `next-env.d.ts` to your `.gitignore`: package.json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start" } } .gitignore # ... .next next-env.d.ts dist Now run `npm run dev`, and open [`http://localhost:3000`](http://localhost:3000). You should see your application now running on Next.js. > **Example:** Check out [this pull request](https://github.com/inngest/vite-to-nextjs/pull/1) for a working example of a Vite application migrated to Next.js. ### [Step 9: Clean Up](#step-9-clean-up) You can now clean up your codebase from Vite related artifacts: * Delete `main.tsx` * Delete `index.html` * Delete `vite-env.d.ts` * Delete `tsconfig.node.json` * Delete `vite.config.ts` * Uninstall Vite dependencies [Next Steps](#next-steps) ------------------------- If everything went according to plan, you now have a functioning Next.js application running as a single-page application. However, you aren't yet taking advantage of most of Next.js' benefits, but you can now start making incremental changes to reap all the benefits. Here's what you might want to do next: * Migrate from React Router to the [Next.js App Router](/docs/app/building-your-application/routing) to get: * Automatic code splitting * [Streaming Server-Rendering](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [React Server Components](/docs/app/building-your-application/rendering/server-components) * [Optimize images with the `<Image>` component](/docs/app/building-your-application/optimizing/images) * [Optimize fonts with `next/font`](/docs/app/building-your-application/optimizing/fonts) * [Optimize third-party scripts with the `<Script>` component](/docs/app/building-your-application/optimizing/scripts) * [Update your ESLint configuration to support Next.js rules](/docs/app/building-your-application/configuring/eslint) [Previous Version 14 ](/docs/app/building-your-application/upgrading/version-14) [Next Migrating from Create React App ](/docs/app/building-your-application/upgrading/from-create-react-app) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"a53f9cf8f01580c73a90e027aa1d76ed\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [ generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Returns](#returns) * [URLs](#urls) * [Example](#example) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/generate-sitemaps.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)generateSitemaps generateSitemaps ================ You can use the `generateSitemaps` function to generate multiple sitemaps for your application. [Returns](#returns) ------------------- The `generateSitemaps` returns an array of objects with an `id` property. [URLs](#urls) ------------- In production, your generated sitemaps will be available at `/.../sitemap/[id].xml`. For example, `/product/sitemap/1.xml`. In development, you can view the generated sitemap on `/.../sitemap.xml/[id]`. For example, `/product/sitemap.xml/1`. This difference is temporary and will follow the production format. [Example](#example) ------------------- For example, to split a sitemap using `generateSitemaps`, return an array of objects with the sitemap `id`. Then, use the `id` to generate the unique sitemaps. app/product/sitemap.ts TypeScript JavaScriptTypeScript import { BASE_URL } from '@/app/lib/constants' export async function generateSitemaps() { // Fetch the total number of products and calculate the number of sitemaps needed return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }] } export default async function sitemap({ id, }: { id: number }): Promise<MetadataRoute.Sitemap> { // Google's limit is 50,000 URLs per sitemap const start = id * 50000 const end = start + 50000 const products = await getProducts( `SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}` ) return products.map((product) => ({ url: `${BASE_URL}/product/${product.id}`, lastModified: product.date, })) } Next Steps ---------- Learn how to create sitemaps for your Next.js application. [ App Router ... Metadata Files ### sitemap.xml API Reference for the sitemap.xml file. ](/docs/app/api-reference/file-conventions/metadata/sitemap) [Previous generateMetadata ](/docs/app/api-reference/functions/generate-metadata) [Next generateStaticParams ](/docs/app/api-reference/functions/generate-static-params) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e6b49dd4ca856167df5693528884d670\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/styling
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/05-styling/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Styling Styling ======= Next.js supports different ways of styling your application, including: * **Global CSS**: Simple to use and familiar for those experienced with traditional CSS, but can lead to larger CSS bundles and difficulty managing styles as the application grows. * **CSS Modules**: Create locally scoped CSS classes to avoid naming conflicts and improve maintainability. * **Tailwind CSS**: A utility-first CSS framework that allows for rapid custom designs by composing utility classes. * **Sass**: A popular CSS preprocessor that extends CSS with features like variables, nested rules, and mixins. * **CSS-in-JS**: Embed CSS directly in your JavaScript components, enabling dynamic and scoped styling. Learn more about each approach by exploring their respective documentation: [ ### CSS Modules Style your Next.js Application with CSS Modules, Global Styles, and external stylesheets. ](/docs/app/building-your-application/styling/css-modules)[ ### Tailwind CSS Style your Next.js Application using Tailwind CSS. ](/docs/app/building-your-application/styling/tailwind-css)[ ### CSS-in-JS Use CSS-in-JS libraries with Next.js ](/docs/app/building-your-application/styling/css-in-js)[ ### Sass Style your Next.js application using Sass. ](/docs/app/building-your-application/styling/sass) [Previous Caching ](/docs/app/building-your-application/caching) [Next CSS Modules ](/docs/app/building-your-application/styling/css-modules) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e2f99fa4f74da843846f89b59cb19397\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/defining-routes
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [ Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Creating Routes](#creating-routes) * [Creating UI](#creating-ui) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/01-defining-routes.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Defining Routes Defining Routes =============== > We recommend reading the [Routing Fundamentals](/docs/app/building-your-application/routing) page before continuing. This page will guide you through how to define and organize routes in your Next.js application. [Creating Routes](#creating-routes) ----------------------------------- Next.js uses a file-system based router where **folders** are used to define routes. Each folder represents a [**route** segment](/docs/app/building-your-application/routing#route-segments) that maps to a **URL** segment. To create a [nested route](/docs/app/building-your-application/routing#nested-routes), you can nest folders inside each other. ![Route segments to path segments](/_next/image?url=%2Fdocs%2Flight%2Froute-segments-to-path-segments.png&w=3840&q=75)![Route segments to path segments](/_next/image?url=%2Fdocs%2Fdark%2Froute-segments-to-path-segments.png&w=3840&q=75) A special [`page.js` file](/docs/app/building-your-application/routing/pages-and-layouts#pages) is used to make route segments publicly accessible. ![Defining Routes](/_next/image?url=%2Fdocs%2Flight%2Fdefining-routes.png&w=3840&q=75)![Defining Routes](/_next/image?url=%2Fdocs%2Fdark%2Fdefining-routes.png&w=3840&q=75) In this example, the `/dashboard/analytics` URL path is _not_ publicly accessible because it does not have a corresponding `page.js` file. This folder could be used to store components, stylesheets, images, or other colocated files. > **Good to know**: `.js`, `.jsx`, or `.tsx` file extensions can be used for special files. [Creating UI](#creating-ui) --------------------------- [Special file conventions](/docs/app/building-your-application/routing#file-conventions) are used to create UI for each route segment. The most common are [pages](/docs/app/building-your-application/routing/pages-and-layouts#pages) to show UI unique to a route, and [layouts](/docs/app/building-your-application/routing/pages-and-layouts#layouts) to show UI that is shared across multiple routes. For example, to create your first page, add a `page.js` file inside the `app` directory and export a React component: app/page.tsx TypeScript JavaScriptTypeScript export default function Page() { return <h1>Hello, Next.js!</h1> } Next Steps ---------- Learn more about creating pages and layouts. [ App Router ... Routing ### Pages and Layouts Create your first page and shared layout with the App Router. ](/docs/app/building-your-application/routing/pages-and-layouts) [Previous Routing ](/docs/app/building-your-application/routing) [Next Pages and Layouts ](/docs/app/building-your-application/routing/pages-and-layouts) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"6c3a3aa4d4f6eed32b54bdb22aed1b1c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [ Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Pages](#pages) * [Layouts](#layouts) * [Root Layout (Required)](#root-layout-required) * [Nesting Layouts](#nesting-layouts) * [Templates](#templates) * [Metadata](#metadata) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/02-pages-and-layouts.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Pages and Layouts Pages and Layouts ================= > We recommend reading the [Routing Fundamentals](/docs/app/building-your-application/routing) and [Defining Routes](/docs/app/building-your-application/routing/defining-routes) pages before continuing. The special files [layout.js](#layouts), [page.js](#pages), and [template.js](#templates) allow you to create UI for a [route](/docs/app/building-your-application/routing/defining-routes#creating-routes). This page will guide you through how and when to use these special files. [Pages](#pages) --------------- A page is UI that is **unique** to a route. You can define a page by default exporting a component from a `page.js` file. For example, to create your `index` page, add the `page.js` file inside the `app` directory: ![page.js special file](/_next/image?url=%2Fdocs%2Flight%2Fpage-special-file.png&w=3840&q=75)![page.js special file](/_next/image?url=%2Fdocs%2Fdark%2Fpage-special-file.png&w=3840&q=75) app/page.tsx TypeScript JavaScriptTypeScript // `app/page.tsx` is the UI for the `/` URL export default function Page() { return <h1>Hello, Home page!</h1> } Then, to create further pages, create a new folder and add the `page.js` file inside it. For example, to create a page for the `/dashboard` route, create a new folder called `dashboard`, and add the `page.js` file inside it: app/dashboard/page.tsx TypeScript JavaScriptTypeScript // `app/dashboard/page.tsx` is the UI for the `/dashboard` URL export default function Page() { return <h1>Hello, Dashboard Page!</h1> } > **Good to know**: > > * The `.js`, `.jsx`, or `.tsx` file extensions can be used for Pages. > * A page is always the [leaf](/docs/app/building-your-application/routing#terminology) of the [route subtree](/docs/app/building-your-application/routing#terminology). > * A `page.js` file is required to make a route segment publicly accessible. > * Pages are [Server Components](/docs/app/building-your-application/rendering/server-components) by default, but can be set to a [Client Component](/docs/app/building-your-application/rendering/client-components). > * Pages can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information. [Layouts](#layouts) ------------------- A layout is UI that is **shared** between multiple routes. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be [nested](#nesting-layouts). You can define a layout by default exporting a React component from a `layout.js` file. The component should accept a `children` prop that will be populated with a child layout (if it exists) or a page during rendering. For example, the layout will be shared with the `/dashboard` and `/dashboard/settings` pages: ![layout.js special file](/_next/image?url=%2Fdocs%2Flight%2Flayout-special-file.png&w=3840&q=75)![layout.js special file](/_next/image?url=%2Fdocs%2Fdark%2Flayout-special-file.png&w=3840&q=75) app/dashboard/layout.tsx TypeScript JavaScriptTypeScript export default function DashboardLayout({ children, // will be a page or nested layout }: { children: React.ReactNode }) { return ( <section> {/* Include shared UI here e.g. a header or sidebar */} <nav></nav> {children} </section> ) } ### [Root Layout (Required)](#root-layout-required) The root layout is defined at the top level of the `app` directory and applies to all routes. This layout is **required** and must contain `html` and `body` tags, allowing you to modify the initial HTML returned from the server. app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body> {/* Layout UI */} <main>{children}</main> </body> </html> ) } ### [Nesting Layouts](#nesting-layouts) By default, layouts in the folder hierarchy are **nested**, which means they wrap child layouts via their `children` prop. You can nest layouts by adding `layout.js` inside specific route segments (folders). For example, to create a layout for the `/dashboard` route, add a new `layout.js` file inside the `dashboard` folder: ![Nested Layout](/_next/image?url=%2Fdocs%2Flight%2Fnested-layout.png&w=3840&q=75)![Nested Layout](/_next/image?url=%2Fdocs%2Fdark%2Fnested-layout.png&w=3840&q=75) app/dashboard/layout.tsx TypeScript JavaScriptTypeScript export default function DashboardLayout({ children, }: { children: React.ReactNode }) { return <section>{children}</section> } If you were to combine the two layouts above, the root layout (`app/layout.js`) would wrap the dashboard layout (`app/dashboard/layout.js`), which would wrap route segments inside `app/dashboard/*`. The two layouts would be nested as such: ![Nested Layouts](/_next/image?url=%2Fdocs%2Flight%2Fnested-layouts-ui.png&w=3840&q=75)![Nested Layouts](/_next/image?url=%2Fdocs%2Fdark%2Fnested-layouts-ui.png&w=3840&q=75) > **Good to know**: > > * `.js`, `.jsx`, or `.tsx` file extensions can be used for Layouts. > * Only the root layout can contain `<html>` and `<body>` tags. > * When a `layout.js` and `page.js` file are defined in the same folder, the layout will wrap the page. > * Layouts are [Server Components](/docs/app/building-your-application/rendering/server-components) by default but can be set to a [Client Component](/docs/app/building-your-application/rendering/client-components). > * Layouts can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information. > * Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/building-your-application/caching#request-memoization) without affecting performance. > * Layouts do not have access to the route segments below itself. To access all route segments, you can use [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) or [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) in a Client Component. > * You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to opt specific route segments in and out of shared layouts. > * You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to create multiple root layouts. See an [example here](/docs/app/building-your-application/routing/route-groups#creating-multiple-root-layouts). > * **Migrating from the `pages` directory:** The root layout replaces the [`_app.js`](/docs/pages/building-your-application/routing/custom-app) and [`_document.js`](/docs/pages/building-your-application/routing/custom-document) files. [View the migration guide](/docs/app/building-your-application/upgrading/app-router-migration#migrating-_documentjs-and-_appjs). [Templates](#templates) ----------------------- Templates are similar to layouts in that they wrap each child layout or page. Unlike layouts that persist across routes and maintain state, templates create a new instance for each of their children on navigation. This means that when a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, state is **not** preserved, and effects are re-synchronized. There may be cases where you need those specific behaviors, and templates would be a more suitable option than layouts. For example: * Features that rely on `useEffect` (e.g logging page views) and `useState` (e.g a per-page feedback form). * To change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when switching pages. For templates, the fallback is shown on each navigation. A template can be defined by exporting a default React component from a `template.js` file. The component should accept a `children` prop. ![template.js special file](/_next/image?url=%2Fdocs%2Flight%2Ftemplate-special-file.png&w=3840&q=75)![template.js special file](/_next/image?url=%2Fdocs%2Fdark%2Ftemplate-special-file.png&w=3840&q=75) app/template.tsx TypeScript JavaScriptTypeScript export default function Template({ children }: { children: React.ReactNode }) { return <div>{children}</div> } In terms of nesting, `template.js` is rendered between a layout and its children. Here's a simplified output: Output <Layout> {/* Note that the template is given a unique key. */} <Template key={routeParam}>{children}</Template> </Layout> [Metadata](#metadata) --------------------- In the `app` directory, you can modify the `<head>` HTML elements such as `title` and `meta` using the [Metadata APIs](/docs/app/building-your-application/optimizing/metadata). Metadata can be defined by exporting a [`metadata` object](/docs/app/api-reference/functions/generate-metadata#the-metadata-object) or [`generateMetadata` function](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) in a [`layout.js`](/docs/app/api-reference/file-conventions/layout) or [`page.js`](/docs/app/api-reference/file-conventions/page) file. app/page.tsx TypeScript JavaScriptTypeScript import { Metadata } from 'next' export const metadata: Metadata = { title: 'Next.js', } export default function Page() { return '...' } > **Good to know**: You should **not** manually add `<head>` tags such as `<title>` and `<meta>` to root layouts. Instead, you should use the [Metadata API](/docs/app/api-reference/functions/generate-metadata) which automatically handles advanced requirements such as streaming and de-duplicating `<head>` elements. Learn more about available metadata options in the [API reference](/docs/app/api-reference/functions/generate-metadata) [Previous Defining Routes ](/docs/app/building-your-application/routing/defining-routes) [Next Linking and Navigating ](/docs/app/building-your-application/routing/linking-and-navigating) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"7d887a752f7d18b953c1f5cf509ea5c4\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/styling/tailwind-css
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [ Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Installing Tailwind](#installing-tailwind) * [Configuring Tailwind](#configuring-tailwind) * [Importing Styles](#importing-styles) * [Using Classes](#using-classes) * [Usage with Turbopack](#usage-with-turbopack) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/05-styling/02-tailwind-css.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Styling](/docs/app/building-your-application/styling)Tailwind CSS Tailwind CSS ============ [Tailwind CSS](https://tailwindcss.com/) is a utility-first CSS framework that works exceptionally well with Next.js. [Installing Tailwind](#installing-tailwind) ------------------------------------------- Install the Tailwind CSS packages and run the `init` command to generate both the `tailwind.config.js` and `postcss.config.js` files: Terminal npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p [Configuring Tailwind](#configuring-tailwind) --------------------------------------------- Inside `tailwind.config.js`, add paths to the files that will use Tailwind CSS class names: tailwind.config.js /** @type {import('tailwindcss').Config} */ module.exports = { content: [ './app/**/*.{js,ts,jsx,tsx,mdx}', // Note the addition of the `app` directory. './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', // Or if using `src` directory: './src/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: {}, }, plugins: [], } You do not need to modify `postcss.config.js`. [Importing Styles](#importing-styles) ------------------------------------- Add the [Tailwind CSS directives](https://tailwindcss.com/docs/functions-and-directives#directives) that Tailwind will use to inject its generated styles to a [Global Stylesheet](/docs/app/building-your-application/styling/css-modules#global-styles) in your application, for example: app/globals.css @tailwind base; @tailwind components; @tailwind utilities; Inside the [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) (`app/layout.tsx`), import the `globals.css` stylesheet to apply the styles to every route in your application. app/layout.tsx TypeScript JavaScriptTypeScript import type { Metadata } from 'next' // These styles apply to every route in the application import './globals.css' export const metadata: Metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> ) } [Using Classes](#using-classes) ------------------------------- After installing Tailwind CSS and adding the global styles, you can use Tailwind's utility classes in your application. app/page.tsx TypeScript JavaScriptTypeScript export default function Page() { return <h1 className="text-3xl font-bold underline">Hello, Next.js!</h1> } [Usage with Turbopack](#usage-with-turbopack) --------------------------------------------- As of Next.js 13.1, Tailwind CSS and PostCSS are supported with [Turbopack](https://turbo.build/pack/docs/features/css#tailwind-css). [Previous CSS Modules ](/docs/app/building-your-application/styling/css-modules) [Next CSS-in-JS ](/docs/app/building-your-application/styling/css-in-js) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"91f26e2dbf3d6d47b57405c0d342a0a1\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [ generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Parameters](#parameters) * [Returns](#returns) * [Single Dynamic Segment](#single-dynamic-segment) * [Multiple Dynamic Segments](#multiple-dynamic-segments) * [Catch-all Dynamic Segment](#catch-all-dynamic-segment) * [Examples](#examples) * [Multiple Dynamic Segments in a Route](#multiple-dynamic-segments-in-a-route) * [Generate params from the bottom up](#generate-params-from-the-bottom-up) * [Generate params from the top down](#generate-params-from-the-top-down) * [Generate only a subset of params](#generate-only-a-subset-of-params) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/generate-static-params.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)generateStaticParams generateStaticParams ==================== The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/building-your-application/routing/dynamic-routes) to [**statically generate**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) routes at build time instead of on-demand at request time. app/blog/\[slug\]/page.js // Return a list of `params` to populate the [slug] dynamic segment export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } // Multiple versions of this page will be statically generated // using the `params` returned by `generateStaticParams` export default function Page({ params }) { const { slug } = params // ... } > **Good to know** > > * You can use the [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams) segment config option to control what happens when a dynamic segment is visited that was not generated with `generateStaticParams`. > * During `next dev`, `generateStaticParams` will be called when you navigate to a route. > * During `next build`, `generateStaticParams` runs before the corresponding Layouts or Pages are generated. > * During revalidation (ISR), `generateStaticParams` will not be called again. > * `generateStaticParams` replaces the [`getStaticPaths`](/docs/pages/api-reference/functions/get-static-paths) function in the Pages Router. [Parameters](#parameters) ------------------------- `options.params` (optional) If multiple dynamic segments in a route use `generateStaticParams`, the child `generateStaticParams` function is executed once for each set of `params` the parent generates. The `params` object contains the populated `params` from the parent `generateStaticParams`, which can be used to [generate the `params` in a child segment](#multiple-dynamic-segments-in-a-route). [Returns](#returns) ------------------- `generateStaticParams` should return an array of objects where each object represents the populated dynamic segments of a single route. * Each property in the object is a dynamic segment to be filled in for the route. * The properties name is the segment's name, and the properties value is what that segment should be filled in with. Example Route `generateStaticParams` Return Type `/product/[id]` `{ id: string }[]` `/products/[category]/[product]` `{ category: string, product: string }[]` `/products/[...slug]` `{ slug: string[] }[]` [Single Dynamic Segment](#single-dynamic-segment) ------------------------------------------------- app/product/\[id\]/page.tsx TypeScript JavaScriptTypeScript export function generateStaticParams() { return [{ id: '1' }, { id: '2' }, { id: '3' }] } // Three versions of this page will be statically generated // using the `params` returned by `generateStaticParams` // - /product/1 // - /product/2 // - /product/3 export default function Page({ params }: { params: { id: string } }) { const { id } = params // ... } [Multiple Dynamic Segments](#multiple-dynamic-segments) ------------------------------------------------------- app/products/\[category\]/\[product\]/page.tsx TypeScript JavaScriptTypeScript export function generateStaticParams() { return [ { category: 'a', product: '1' }, { category: 'b', product: '2' }, { category: 'c', product: '3' }, ] } // Three versions of this page will be statically generated // using the `params` returned by `generateStaticParams` // - /products/a/1 // - /products/b/2 // - /products/c/3 export default function Page({ params, }: { params: { category: string; product: string } }) { const { category, product } = params // ... } [Catch-all Dynamic Segment](#catch-all-dynamic-segment) ------------------------------------------------------- app/product/\[...slug\]/page.tsx TypeScript JavaScriptTypeScript export function generateStaticParams() { return [{ slug: ['a', '1'] }, { slug: ['b', '2'] }, { slug: ['c', '3'] }] } // Three versions of this page will be statically generated // using the `params` returned by `generateStaticParams` // - /product/a/1 // - /product/b/2 // - /product/c/3 export default function Page({ params }: { params: { slug: string[] } }) { const { slug } = params // ... } [Examples](#examples) --------------------- ### [Multiple Dynamic Segments in a Route](#multiple-dynamic-segments-in-a-route) You can generate params for dynamic segments above the current layout or page, but **not below**. For example, given the `app/products/[category]/[product]` route: * `app/products/[category]/[product]/page.js` can generate params for **both** `[category]` and `[product]`. * `app/products/[category]/layout.js` can **only** generate params for `[category]`. There are two approaches to generating params for a route with multiple dynamic segments: ### [Generate params from the bottom up](#generate-params-from-the-bottom-up) Generate multiple dynamic segments from the child route segment. app/products/\[category\]/\[product\]/page.tsx TypeScript JavaScriptTypeScript // Generate segments for both [category] and [product] export async function generateStaticParams() { const products = await fetch('https://.../products').then((res) => res.json()) return products.map((product) => ({ category: product.category.slug, product: product.id, })) } export default function Page({ params, }: { params: { category: string; product: string } }) { // ... } ### [Generate params from the top down](#generate-params-from-the-top-down) Generate the parent segments first and use the result to generate the child segments. app/products/\[category\]/layout.tsx TypeScript JavaScriptTypeScript // Generate segments for [category] export async function generateStaticParams() { const products = await fetch('https://.../products').then((res) => res.json()) return products.map((product) => ({ category: product.category.slug, })) } export default function Layout({ params }: { params: { category: string } }) { // ... } A child route segment's `generateStaticParams` function is executed once for each segment a parent `generateStaticParams` generates. The child `generateStaticParams` function can use the `params` returned from the parent `generateStaticParams` function to dynamically generate its own segments. app/products/\[category\]/\[product\]/page.tsx TypeScript JavaScriptTypeScript // Generate segments for [product] using the `params` passed from // the parent segment's `generateStaticParams` function export async function generateStaticParams({ params: { category }, }: { params: { category: string } }) { const products = await fetch( `https://.../products?category=${category}` ).then((res) => res.json()) return products.map((product) => ({ product: product.id, })) } export default function Page({ params, }: { params: { category: string; product: string } }) { // ... } > **Good to know**: `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across all `generate`\-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable. ### [Generate only a subset of params](#generate-only-a-subset-of-params) You can generate a subset of params for a route by returning an array of objects with only the dynamic segments you want to generate. Then, by using the [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams) segment config option, you can control what happens when a dynamic segment is visited that was not generated with `generateStaticParams`. app/blog/\[slug\]/page.js // All posts besides the top 10 will be a 404 export const dynamicParams = false export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) const topPosts = posts.slice(0, 10) return topPosts.map((post) => ({ slug: post.slug, })) } [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `generateStaticParams` introduced. [Previous generateSitemaps ](/docs/app/api-reference/functions/generate-sitemaps) [Next generateViewport ](/docs/app/api-reference/functions/generate-viewport) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"67fc643574c40a8b17c94b4e02ec7c4d\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/static-assets
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [ Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Caching](#caching) * [Robots, Favicons, and others](#robots-favicons-and-others) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/11-static-assets.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Static Assets Static Assets in \`public\` =========================== Next.js can serve static files, like images, under a folder called `public` in the root directory. Files inside `public` can then be referenced by your code starting from the base URL (`/`). For example, the file `public/avatars/me.png` can be viewed by visiting the `/avatars/me.png` path. The code to display that image might look like: avatar.js import Image from 'next/image' export function Avatar({ id, alt }) { return <Image src={`/avatars/${id}.png`} alt={alt} width="64" height="64" /> } export function AvatarOfMe() { return <Avatar id="me" alt="A portrait of me" /> } [Caching](#caching) ------------------- Next.js cannot safely cache assets in the `public` folder because they may change. The default caching headers applied are: Cache-Control: public, max-age=0 [Robots, Favicons, and others](#robots-favicons-and-others) ----------------------------------------------------------- For static metadata files, such as `robots.txt`, `favicon.ico`, etc, you should use [special metadata files](/docs/app/api-reference/file-conventions/metadata) inside the `app` folder. > Good to know: > > * The directory must be named `public`. The name cannot be changed and it's the only directory used to serve static assets. > * Only assets that are in the `public` directory at [build time](/docs/app/api-reference/next-cli#build) will be served by Next.js. Files added at request time won't be available. We recommend using a third-party service like [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) for persistent file storage. [Previous OpenTelemetry ](/docs/app/building-your-application/optimizing/open-telemetry) [Next Third Party Libraries ](/docs/app/building-your-application/optimizing/third-party-libraries) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"2da1602592a3130c2e231d5c9e819eb1\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/styling/css-modules
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [ CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [CSS Modules](#css-modules) * [Example](#example) * [Global Styles](#global-styles) * [External Stylesheets](#external-stylesheets) * [Ordering and Merging](#ordering-and-merging) * [Additional Features](#additional-features) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/05-styling/01-css-modules.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Styling](/docs/app/building-your-application/styling)CSS Modules CSS Modules and Global Styles ============================= Next.js supports different types of stylesheets, including: * [CSS Modules](#css-modules) * [Global Styles](#global-styles) * [External Stylesheets](#external-stylesheets) [CSS Modules](#css-modules) --------------------------- Next.js has built-in support for CSS Modules using the `.module.css` extension. CSS Modules locally scope CSS by automatically creating a unique class name. This allows you to use the same class name in different files without worrying about collisions. This behavior makes CSS Modules the ideal way to include component-level CSS. [Example](#example) ------------------- CSS Modules can be imported into any file inside the `app` directory: app/dashboard/layout.tsx TypeScript JavaScriptTypeScript import styles from './styles.module.css' export default function DashboardLayout({ children, }: { children: React.ReactNode }) { return <section className={styles.dashboard}>{children}</section> } app/dashboard/styles.module.css .dashboard { padding: 24px; } CSS Modules are **only enabled for files with the `.module.css` and `.module.sass` extensions**. In production, all CSS Module files will be automatically concatenated into **many minified and code-split** `.css` files. These `.css` files represent hot execution paths in your application, ensuring the minimal amount of CSS is loaded for your application to paint. [Global Styles](#global-styles) ------------------------------- Global styles can be imported into any layout, page, or component inside the `app` directory. > **Good to know**: This is different from the `pages` directory, where you can only import global styles inside the `_app.js` file. For example, consider a stylesheet named `app/global.css`: body { padding: 20px 20px 60px; max-width: 680px; margin: 0 auto; } Inside the root layout (`app/layout.js`), import the `global.css` stylesheet to apply the styles to every route in your application: app/layout.tsx TypeScript JavaScriptTypeScript // These styles apply to every route in the application import './global.css' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> ) } [External Stylesheets](#external-stylesheets) --------------------------------------------- Stylesheets published by external packages can be imported anywhere in the `app` directory, including colocated components: app/layout.tsx TypeScript JavaScriptTypeScript import 'bootstrap/dist/css/bootstrap.css' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body className="container">{children}</body> </html> ) } > **Good to know**: External stylesheets must be directly imported from an npm package or downloaded and colocated with your codebase. You cannot use `<link rel="stylesheet" />`. [Ordering and Merging](#ordering-and-merging) --------------------------------------------- Next.js optimizes CSS during production builds by automatically chunking (merging) stylesheets. The CSS order is determined by the order in which you import the stylesheets into your application code. For example, `base-button.module.css` will be ordered before `page.module.css` since `<BaseButton>` is imported first in `<Page>`: base-button.tsx TypeScript JavaScriptTypeScript import styles from './base-button.module.css' export function BaseButton() { return <button className={styles.primary} /> } page.ts TypeScript JavaScriptTypeScript import { BaseButton } from './base-button' import styles from './page.module.css' export function Page() { return <BaseButton className={styles.primary} /> } To maintain a predictable order, we recommend the following: * Only import a CSS file in a single JS/TS file. * If using global class names, import the global styles in the same file in the order you want them to be applied. * Prefer CSS Modules over global styles. * Use a consistent naming convention for your CSS modules. For example, using `<name>.module.css` over `<name>.tsx`. * Extract shared styles into a separate shared component. * If using [Tailwind](/docs/app/building-your-application/styling/tailwind-css), import the stylesheet at the top of the file, preferably in the [Root Layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required). > **Good to know:** CSS ordering behaves differently in development mode, always ensure to check preview deployments to verify the final CSS order in your production build. [Additional Features](#additional-features) ------------------------------------------- Next.js includes additional features to improve the authoring experience of adding styles: * When running locally with `next dev`, local stylesheets (either global or CSS modules) will take advantage of [Fast Refresh](/docs/architecture/fast-refresh) to instantly reflect changes as edits are saved. * When building for production with `next build`, CSS files will be bundled into fewer minified `.css` files to reduce the number of network requests needed to retrieve styles. * If you disable JavaScript, styles will still be loaded in the production build (`next start`). However, JavaScript is still required for `next dev` to enable [Fast Refresh](/docs/architecture/fast-refresh). [Previous Styling ](/docs/app/building-your-application/styling) [Next Tailwind CSS ](/docs/app/building-your-application/styling/tailwind-css) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"a405109a3221853819b7f2fa7a38364d\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/third-party-libraries
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [ Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Getting Started](#getting-started) * [Google Third-Parties](#google-third-parties) * [Google Tag Manager](#google-tag-manager) * [Sending Events](#sending-events) * [Options](#options) * [Google Analytics](#google-analytics) * [Sending Events](#sending-events-1) * [Tracking Pageviews](#tracking-pageviews) * [Options](#options-1) * [Google Maps Embed](#google-maps-embed) * [Options](#options-2) * [YouTube Embed](#youtube-embed) * [Options](#options-3) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/12-third-party-libraries.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Third Party Libraries Third Party Libraries ===================== **`@next/third-parties`** is a library that provides a collection of components and utilities that improve the performance and developer experience of loading popular third-party libraries in your Next.js application. All third-party integrations provided by `@next/third-parties` have been optimized for performance and ease of use. [Getting Started](#getting-started) ----------------------------------- To get started, install the `@next/third-parties` library: Terminal npm install @next/third-parties@latest next@latest `@next/third-parties` is currently an **experimental** library under active development. We recommend installing it with the **latest** or **canary** flags while we work on adding more third-party integrations. [Google Third-Parties](#google-third-parties) --------------------------------------------- All supported third-party libraries from Google can be imported from `@next/third-parties/google`. ### [Google Tag Manager](#google-tag-manager) The `GoogleTagManager` component can be used to instantiate a [Google Tag Manager](https://developers.google.com/tag-platform/tag-manager) container to your page. By default, it fetches the original inline script after hydration occurs on the page. To load Google Tag Manager for all routes, include the component directly in your root layout and pass in your GTM container ID: app/layout.tsx TypeScript JavaScriptTypeScript import { GoogleTagManager } from '@next/third-parties/google' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <GoogleTagManager gtmId="GTM-XYZ" /> <body>{children}</body> </html> ) } To load Google Tag Manager for a single route, include the component in your page file: app/page.js import { GoogleTagManager } from '@next/third-parties/google' export default function Page() { return <GoogleTagManager gtmId="GTM-XYZ" /> } #### [Sending Events](#sending-events) The `sendGTMEvent` function can be used to track user interactions on your page by sending events using the `dataLayer` object. For this function to work, the `<GoogleTagManager />` component must be included in either a parent layout, page, or component, or directly in the same file. app/page.js 'use client' import { sendGTMEvent } from '@next/third-parties/google' export function EventButton() { return ( <div> <button onClick={() => sendGTMEvent({ event: 'buttonClicked', value: 'xyz' })} > Send Event </button> </div> ) } Refer to the Tag Manager [developer documentation](https://developers.google.com/tag-platform/tag-manager/datalayer) to learn about the different variables and events that can be passed into the function. #### [Options](#options) Options to pass to the Google Tag Manager. For a full list of options, read the [Google Tag Manager docs](https://developers.google.com/tag-platform/tag-manager/datalayer). Name Type Description `gtmId` Required Your GTM container ID. Usually starts with `GTM-`. `dataLayer` Optional Data layer array to instantiate the container with. Defaults to an empty array. `dataLayerName` Optional Name of the data layer. Defaults to `dataLayer`. `auth` Optional Value of authentication parameter (`gtm_auth`) for environment snippets. `preview` Optional Value of preview parameter (`gtm_preview`) for environment snippets. ### [Google Analytics](#google-analytics) The `GoogleAnalytics` component can be used to include [Google Analytics 4](https://developers.google.com/analytics/devguides/collection/ga4) to your page via the Google tag (`gtag.js`). By default, it fetches the original scripts after hydration occurs on the page. > **Recommendation**: If Google Tag Manager is already included in your application, you can configure Google Analytics directly using it, rather than including Google Analytics as a separate component. Refer to the [documentation](https://developers.google.com/analytics/devguides/collection/ga4/tag-options#what-is-gtm) to learn more about the differences between Tag Manager and `gtag.js`. To load Google Analytics for all routes, include the component directly in your root layout and pass in your measurement ID: app/layout.tsx TypeScript JavaScriptTypeScript import { GoogleAnalytics } from '@next/third-parties/google' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> <GoogleAnalytics gaId="G-XYZ" /> </html> ) } To load Google Analytics for a single route, include the component in your page file: app/page.js import { GoogleAnalytics } from '@next/third-parties/google' export default function Page() { return <GoogleAnalytics gaId="G-XYZ" /> } #### [Sending Events](#sending-events-1) The `sendGAEvent` function can be used to measure user interactions on your page by sending events using the `dataLayer` object. For this function to work, the `<GoogleAnalytics />` component must be included in either a parent layout, page, or component, or directly in the same file. app/page.js 'use client' import { sendGAEvent } from '@next/third-parties/google' export function EventButton() { return ( <div> <button onClick={() => sendGAEvent({ event: 'buttonClicked', value: 'xyz' })} > Send Event </button> </div> ) } Refer to the Google Analytics [developer documentation](https://developers.google.com/analytics/devguides/collection/ga4/event-parameters) to learn more about event parameters. #### [Tracking Pageviews](#tracking-pageviews) Google Analytics automatically tracks pageviews when the browser history state changes. This means that client-side navigations between Next.js routes will send pageview data without any configuration. To ensure that client-side navigations are being measured correctly, verify that the [_“Enhanced Measurement”_](https://support.google.com/analytics/answer/9216061#enable_disable) property is enabled in your Admin panel and the _“Page changes based on browser history events”_ checkbox is selected. > **Note**: If you decide to manually send pageview events, make sure to disable the default pageview measurement to avoid having duplicate data. Refer to the Google Analytics [developer documentation](https://developers.google.com/analytics/devguides/collection/ga4/views?client_type=gtag#manual_pageviews) to learn more. #### [Options](#options-1) Options to pass to the `<GoogleAnalytics>` component. Name Type Description `gaId` Required Your [measurement ID](https://support.google.com/analytics/answer/12270356). Usually starts with `G-`. `dataLayerName` Optional Name of the data layer. Defaults to `dataLayer`. ### [Google Maps Embed](#google-maps-embed) The `GoogleMapsEmbed` component can be used to add a [Google Maps Embed](https://developers.google.com/maps/documentation/embed/embedding-map) to your page. By default, it uses the `loading` attribute to lazy-load the embed below the fold. app/page.js import { GoogleMapsEmbed } from '@next/third-parties/google' export default function Page() { return ( <GoogleMapsEmbed apiKey="XYZ" height={200} width="100%" mode="place" q="Brooklyn+Bridge,New+York,NY" /> ) } #### [Options](#options-2) Options to pass to the Google Maps Embed. For a full list of options, read the [Google Map Embed docs](https://developers.google.com/maps/documentation/embed/embedding-map). Name Type Description `apiKey` Required Your api key. `mode` Required [Map mode](https://developers.google.com/maps/documentation/embed/embedding-map#choosing_map_modes) `height` Optional Height of the embed. Defaults to `auto`. `width` Optional Width of the embed. Defaults to `auto`. `style` Optional Pass styles to the iframe. `allowfullscreen` Optional Property to allow certain map parts to go full screen. `loading` Optional Defaults to lazy. Consider changing if you know your embed will be above the fold. `q` Optional Defines map marker location. _This may be required depending on the map mode_. `center` Optional Defines the center of the map view. `zoom` Optional Sets initial zoom level of the map. `maptype` Optional Defines type of map tiles to load. `language` Optional Defines the language to use for UI elements and for the display of labels on map tiles. `region` Optional Defines the appropriate borders and labels to display, based on geo-political sensitivities. ### [YouTube Embed](#youtube-embed) The `YouTubeEmbed` component can be used to load and display a YouTube embed. This component loads faster by using [`lite-youtube-embed`](https://github.com/paulirish/lite-youtube-embed) under the hood. app/page.js import { YouTubeEmbed } from '@next/third-parties/google' export default function Page() { return <YouTubeEmbed videoid="ogfYd705cRs" height={400} params="controls=0" /> } #### [Options](#options-3) Name Type Description `videoid` Required YouTube video id. `width` Optional Width of the video container. Defaults to `auto` `height` Optional Height of the video container. Defaults to `auto` `playlabel` Optional A visually hidden label for the play button for accessibility. `params` Optional The video player params defined [here](https://developers.google.com/youtube/player_parameters#Parameters). Params are passed as a query param string. Eg: `params="controls=0&start=10&end=30"` `style` Optional Used to apply styles to the video container. [Previous Static Assets ](/docs/app/building-your-application/optimizing/static-assets) [Next Memory Usage ](/docs/app/building-your-application/optimizing/memory-usage) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"5cefcecf0f0d49ea20166a673647184b\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/upgrading/from-create-react-app
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [ Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Why Switch?](#why-switch) * [Slow initial page loading time](#slow-initial-page-loading-time) * [No automatic code splitting](#no-automatic-code-splitting) * [Network waterfalls](#network-waterfalls) * [Fast and intentional loading states](#fast-and-intentional-loading-states) * [Choose the data fetching strategy](#choose-the-data-fetching-strategy) * [Middleware](#middleware) * [Built-in Optimizations](#built-in-optimizations) * [Migration Steps](#migration-steps) * [Step 1: Install the Next.js Dependency](#step-1-install-the-nextjs-dependency) * [Step 2: Create the Next.js Configuration File](#step-2-create-the-nextjs-configuration-file) * [Step 3: Update TypeScript Configuration](#step-3-update-typescript-configuration) * [Step 4: Create the Root Layout](#step-4-create-the-root-layout) * [Step 5: Metadata](#step-5-metadata) * [Step 6: Styles](#step-6-styles) * [Step 7: Create the Entrypoint Page](#step-7-create-the-entrypoint-page) * [Step 8: Update Static Image Imports](#step-8-update-static-image-imports) * [Step 9: Migrate the Environment Variables](#step-9-migrate-the-environment-variables) * [Step 10: Update Scripts in package.json](#step-10-update-scripts-in-packagejson) * [Step 11: Clean Up](#step-11-clean-up) * [Bundler Compatibility](#bundler-compatibility) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/11-upgrading/05-from-create-react-app.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Upgrading](/docs/app/building-your-application/upgrading)Migrating from Create React App Migrating from Create React App =============================== This guide will help you migrate an existing Create React App site to Next.js. [Why Switch?](#why-switch) -------------------------- There are several reasons why you might want to switch from Create React App to Next.js: ### [Slow initial page loading time](#slow-initial-page-loading-time) Create React App uses purely client-side React. Client-side only applications, also known as single-page applications (SPAs), often experience slow initial page loading time. This happens due to a couple of reasons: 1. The browser needs to wait for the React code and your entire application bundle to download and run before your code is able to send requests to load data. 2. Your application code grows with every new feature and dependency you add. ### [No automatic code splitting](#no-automatic-code-splitting) The previous issue of slow loading times can be somewhat managed with code splitting. However, if you try to do code splitting manually, you'll often make performance worse. It's easy to inadvertently introduce network waterfalls when code-splitting manually. Next.js provides automatic code splitting built into its router. ### [Network waterfalls](#network-waterfalls) A common cause of poor performance occurs when applications make sequential client-server requests to fetch data. One common pattern for data fetching in an SPA is to initially render a placeholder, and then fetch data after the component has mounted. Unfortunately, this means that a child component that fetches data can't start fetching until the parent component has finished loading its own data. While fetching data on the client is supported with Next.js, it also gives you the option to shift data fetching to the server, which can eliminate client-server waterfalls. ### [Fast and intentional loading states](#fast-and-intentional-loading-states) With built-in support for [streaming through React Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense), you can be more intentional about which parts of your UI you want to load first and in what order without introducing network waterfalls. This enables you to build pages that are faster to load and eliminate [layout shifts](https://vercel.com/blog/how-core-web-vitals-affect-seo). ### [Choose the data fetching strategy](#choose-the-data-fetching-strategy) Depending on your needs, Next.js allows you to choose your data fetching strategy on a page and component basis. You can decide to fetch at build time, at request time on the server, or on the client. For example, you can fetch data from your CMS and render your blog posts at build time, which can then be efficiently cached on a CDN. ### [Middleware](#middleware) [Next.js Middleware](/docs/app/building-your-application/routing/middleware) allows you to run code on the server before a request is completed. This is especially useful to avoid having a flash of unauthenticated content when the user visits an authenticated-only page by redirecting the user to a login page. The middleware is also useful for experimentation and [internationalization](/docs/app/building-your-application/routing/internationalization). ### [Built-in Optimizations](#built-in-optimizations) [Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/building-your-application/optimizing/scripts) often have significant impact on an application's performance. Next.js comes with built-in components that automatically optimize those for you. [Migration Steps](#migration-steps) ----------------------------------- Our goal with this migration is to get a working Next.js application as quickly as possible, so that you can then adopt Next.js features incrementally. To begin with, we'll keep it as a purely client-side application (SPA) without migrating your existing router. This helps minimize the chances of encountering issues during the migration process and reduces merge conflicts. ### [Step 1: Install the Next.js Dependency](#step-1-install-the-nextjs-dependency) The first thing you need to do is to install `next` as a dependency: Terminal npm install next@latest ### [Step 2: Create the Next.js Configuration File](#step-2-create-the-nextjs-configuration-file) Create a `next.config.mjs` at the root of your project. This file will hold your [Next.js configuration options](/docs/app/api-reference/next-config-js). next.config.mjs /** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // Outputs a Single-Page Application (SPA). distDir: './dist', // Changes the build output directory to `./dist/`. } export default nextConfig ### [Step 3: Update TypeScript Configuration](#step-3-update-typescript-configuration) If you're using TypeScript, you need to update your `tsconfig.json` file with the following changes to make it compatible with Next.js: tsconfig.json { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "baseUrl": ".", "incremental": true, "plugins": [ { "name": "next" } ], "strictNullChecks": true }, "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "./dist/types/**/*.ts" ], "exclude": ["node_modules"] } You can find more information about configuring TypeScript on the [Next.js docs](/docs/app/building-your-application/configuring/typescript#typescript-plugin). ### [Step 4: Create the Root Layout](#step-4-create-the-root-layout) A Next.js [App Router](/docs/app) application must include a [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) file, which is a [React Server Component](/docs/app/building-your-application/rendering/server-components) that will wrap all pages in your application. This file is defined at the top level of the `app` directory. The closest equivalent to the root layout file in a CRA application is the `index.html` file, which contains your `<html>`, `<head>`, and `<body>` tags. In this step, you'll convert your `index.html` file into a root layout file: 1. Create a new `app` directory in your `src` directory. 2. Create a new `layout.tsx` file inside that `app` directory: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return null } > **Good to know**: `.js`, `.jsx`, or `.tsx` extensions can be used for Layout files. Copy the content of your `index.html` file into the previously created `<RootLayout>` component while replacing the `body.div#root` and `body.script` tags with `<div id="root">{children}</div>`: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>React App</title> <meta name="description" content="Web site created..." /> </head> <body> <div id="root">{children}</div> </body> </html> ) } > **Good to know**: We'll ignore the [manifest file](/docs/app/api-reference/file-conventions/metadata), additional iconography other than the favicon, and [testing configuration](/docs/app/building-your-application/testing), but if these are requirements, Next.js also supports these options. ### [Step 5: Metadata](#step-5-metadata) Next.js already includes by default the [meta charset](https://developer.mozilla.org/docs/Web/HTML/Element/meta#charset) and [meta viewport](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag) tags, so you can safely remove those from your `<head>`: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <head> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <title>React App</title> <meta name="description" content="Web site created..." /> </head> <body> <div id="root">{children}</div> </body> </html> ) } Any [metadata files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) such as `favicon.ico`, `icon.png`, `robots.txt` are automatically added to the application `<head>` tag as long as you have them placed into the top level of the `app` directory. After moving [all supported files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) into the `app` directory you can safely delete their `<link>` tags: app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <head> <title>React App</title> <meta name="description" content="Web site created..." /> </head> <body> <div id="root">{children}</div> </body> </html> ) } Finally, Next.js can manage your last `<head>` tags with the [Metadata API](/docs/app/building-your-application/optimizing/metadata). Move your final metadata info into an exported [`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object): app/layout.tsx TypeScript JavaScriptTypeScript import type { Metadata } from 'next' export const metadata: Metadata = { title: 'React App', description: 'Web site created with Next.js.', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <div id="root">{children}</div> </body> </html> ) } With the above changes, you shifted from declaring everything in your `index.html` to using Next.js' convention-based approach built into the framework ([Metadata API](/docs/app/building-your-application/optimizing/metadata)). This approach enables you to more easily improve your SEO and web shareability of your pages. ### [Step 6: Styles](#step-6-styles) Like Create React App, Next.js has built-in support for [CSS Modules](/docs/app/building-your-application/styling/css-modules). If you're using a global CSS file, import it into your `app/layout.tsx` file: app/layout.tsx TypeScript JavaScriptTypeScript import '../index.css' // ... If you're using Tailwind, you'll need to install `postcss` and `autoprefixer`: Terminal npm install postcss autoprefixer Then, create a `postcss.config.js` file at the root of your project: postcss.config.js module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, } ### [Step 7: Create the Entrypoint Page](#step-7-create-the-entrypoint-page) On Next.js you declare an entrypoint for your application by creating a `page.tsx` file. The closest equivalent of this file on CRA is your `src/index.tsx` file. In this step, you’ll set up the entry point of your application. **Create a `[[...slug]]` directory in your `app` directory.** Since this guide is aiming to first set up our Next.js as an SPA (Single Page Application), you need your page entry point to catch all possible routes of your application. For that, create a new `[[...slug]]` directory in your `app` directory. This directory is what is called an [optional catch-all route segment](/docs/app/building-your-application/routing/dynamic-routes#optional-catch-all-segments). Next.js uses a file-system based router where [directories are used to define routes](/docs/app/building-your-application/routing/defining-routes#creating-routes). This special directory will make sure that all routes of your application will be directed to its containing `page.tsx` file. **Create a new `page.tsx` file inside the `app/[[...slug]]` directory with the following content:** app/\[\[...slug\]\]/page.tsx TypeScript JavaScriptTypeScript import '../../index.css' export function generateStaticParams() { return [{ slug: [''] }] } export default function Page() { return '...' // We'll update this } This file is a [Server Component](/docs/app/building-your-application/rendering/server-components). When you run `next build`, the file is prerendered into a static asset. It does _not_ require any dynamic code. This file imports our global CSS and tells [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) we are only going to generate one route, the index route at `/`. Now, let's move the rest of our CRA application which will run client-only. app/\[\[...slug\]\]/client.tsx TypeScript JavaScriptTypeScript 'use client' import React from 'react' import dynamic from 'next/dynamic' const App = dynamic(() => import('../../App'), { ssr: false }) export function ClientOnly() { return <App /> } This file is a [Client Component](/docs/app/building-your-application/rendering/client-components), defined by the `'use client'` directive. Client Components are still [prerendered to HTML](/docs/app/building-your-application/rendering/client-components#how-are-client-components-rendered) on the server before being sent to the client. Since we want a client-only application to start, we can configure Next.js to disable prerendering from the `App` component down. const App = dynamic(() => import('../../App'), { ssr: false }) Now, update your entrypoint page to use the new component: app/\[\[...slug\]\]/page.tsx TypeScript JavaScriptTypeScript import '../../index.css' import { ClientOnly } from './client' export function generateStaticParams() { return [{ slug: [''] }] } export default function Page() { return <ClientOnly /> } ### [Step 8: Update Static Image Imports](#step-8-update-static-image-imports) Next.js handles static image imports slightly different from CRA. With CRA, importing an image file will return its public URL as a string: App.tsx import image from './img.png' export default function App() { return <img src={image} /> } With Next.js, static image imports return an object. The object can then be used directly with the Next.js [`<Image>` component](/docs/app/api-reference/components/image), or you can use the object's `src` property with your existing `<img>` tag. The `<Image>` component has the added benefits of [automatic image optimization](/docs/app/building-your-application/optimizing/images). The `<Image>` component automatically sets the `width` and `height` attributes of the resulting `<img>` based on the image's dimensions. This prevents layout shifts when the image loads. However, this can cause issues if your app contains images with only one of their dimensions being styled without the other styled to `auto`. When not styled to `auto`, the dimension will default to the `<img>` dimension attribute's value, which can cause the image to appear distorted. Keeping the `<img>` tag will reduce the amount of changes in your application and prevent the above issues. You can then optionally later migrate to the `<Image>` component to take advantage of optimizing images by [configuring a loader](/docs/app/building-your-application/optimizing/images#loaders), or moving to the default Next.js server which has automatic image optimization. **Convert absolute import paths for images imported from `/public` into relative imports:** // Before import logo from '/logo.png' // After import logo from '../public/logo.png' **Pass the image `src` property instead of the whole image object to your `<img>` tag:** // Before <img src={logo} /> // After <img src={logo.src} /> Alternatively, you can reference the public URL for the image asset based on the filename. For example, `public/logo.png` will serve the image at `/logo.png` for your application, which would be the `src` value. > **Warning:** If you're using TypeScript, you might encounter type errors when accessing the `src` property. You can safely ignore those for now. They will be fixed by the end of this guide. ### [Step 9: Migrate the Environment Variables](#step-9-migrate-the-environment-variables) Next.js has support for `.env` [environment variables](/docs/app/building-your-application/configuring/environment-variables) similar to CRA. The main difference is the prefix used to expose environment variables on the client-side. Change all environment variables with the `REACT_APP_` prefix to `NEXT_PUBLIC_`. ### [Step 10: Update Scripts in `package.json`](#step-10-update-scripts-in-packagejson) You should now be able to run your application to test if you successfully migrated to Next.js. But before that, you need to update your `scripts` in your `package.json` with Next.js related commands, and add `.next`, `next-env.d.ts`, and `dist` to your `.gitignore` file: package.json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start" } } .gitignore # ... .next next-env.d.ts dist Now run `npm run dev`, and open [`http://localhost:3000`](http://localhost:3000). You should see your application now running on Next.js. ### [Step 11: Clean Up](#step-11-clean-up) You can now clean up your codebase from Create React App related artifacts: * Delete `src/index.tsx` * Delete `public/index.html` * Delete `reportWebVitals` setup * Uninstall CRA dependencies (`react-scripts`) [Bundler Compatibility](#bundler-compatibility) ----------------------------------------------- Create React App and Next.js both default to using webpack for bundling. When migrating your CRA application to Next.js, you might have a custom webpack configuration you're looking to migrate. Next.js supports providing a [custom webpack configuration](/docs/app/api-reference/next-config-js/webpack). Further, Next.js has support for [Turbopack](/docs/app/api-reference/next-config-js/turbo) through `next dev --turbo` to improve your local dev performance. Turbopack supports some [webpack loaders](/docs/app/api-reference/next-config-js/turbo) as well for compatibility and incremental adoption. [Next Steps](#next-steps) ------------------------- If everything went according to plan, you now have a functioning Next.js application running as a single-page application. However, you aren't yet taking advantage of most of Next.js' benefits, but you can now start making incremental changes to reap all the benefits. Here's what you might want to do next: * Migrate from React Router to the [Next.js App Router](/docs/app/building-your-application/routing) to get: * Automatic code splitting * [Streaming Server-Rendering](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [React Server Components](/docs/app/building-your-application/rendering/server-components) * [Optimize images with the `<Image>` component](/docs/app/building-your-application/optimizing/images) * [Optimize fonts with `next/font`](/docs/app/building-your-application/optimizing/fonts) * [Optimize third-party scripts with the `<Script>` component](/docs/app/building-your-application/optimizing/scripts) * [Update your ESLint configuration to support Next.js rules](/docs/app/building-your-application/configuring/eslint) > **Good to know:** Using a static export [does not currently support](https://github.com/vercel/next.js/issues/54393) using the `useParams` hook. [Previous Migrating from Vite ](/docs/app/building-your-application/upgrading/from-vite) [Next API Reference ](/docs/app/api-reference) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e0dff8419a3c74f724863cc912790289\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [ Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [<Link> Component](#link-component) * [Examples](#examples) * [Linking to Dynamic Segments](#linking-to-dynamic-segments) * [Checking Active Links](#checking-active-links) * [Scrolling to an id](#scrolling-to-an-id) * [Disabling scroll restoration](#disabling-scroll-restoration) * [useRouter() hook](#userouter-hook) * [redirect function](#redirect-function) * [Using the native History API](#using-the-native-history-api) * [window.history.pushState](#windowhistorypushstate) * [window.history.replaceState](#windowhistoryreplacestate) * [How Routing and Navigation Works](#how-routing-and-navigation-works) * [1\. Code Splitting](#1-code-splitting) * [2\. Prefetching](#2-prefetching) * [3\. Caching](#3-caching) * [4\. Partial Rendering](#4-partial-rendering) * [5\. Soft Navigation](#5-soft-navigation) * [6\. Back and Forward Navigation](#6-back-and-forward-navigation) * [7\. Routing between pages/ and app/](#7-routing-between-pages-and-app) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Linking and Navigating Linking and Navigating ====================== There are four ways to navigate between routes in Next.js: * Using the [`<Link>` Component](#link-component) * Using the [`useRouter` hook](#userouter-hook) ([Client Components](/docs/app/building-your-application/rendering/client-components)) * Using the [`redirect` function](#redirect-function) ([Server Components](/docs/app/building-your-application/rendering/server-components)) * Using the native [History API](#using-the-native-history-api) This page will go through how to use each of these options, and dive deeper into how navigation works. [`<Link>` Component](#link-component) ------------------------------------- `<Link>` is a built-in component that extends the HTML `<a>` tag to provide [prefetching](#2-prefetching) and client-side navigation between routes. It is the primary and recommended way to navigate between routes in Next.js. You can use it by importing it from `next/link`, and passing a `href` prop to the component: app/page.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Page() { return <Link href="/dashboard">Dashboard</Link> } There are other optional props you can pass to `<Link>`. See the [API reference](/docs/app/api-reference/components/link) for more. ### [Examples](#examples) #### [Linking to Dynamic Segments](#linking-to-dynamic-segments) When linking to [dynamic segments](/docs/app/building-your-application/routing/dynamic-routes), you can use [template literals and interpolation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals) to generate a list of links. For example, to generate a list of blog posts: app/blog/PostList.js import Link from 'next/link' export default function PostList({ posts }) { return ( <ul> {posts.map((post) => ( <li key={post.id}> <Link href={`/blog/${post.slug}`}>{post.title}</Link> </li> ))} </ul> ) } #### [Checking Active Links](#checking-active-links) You can use [`usePathname()`](/docs/app/api-reference/functions/use-pathname) to determine if a link is active. For example, to add a class to the active link, you can check if the current `pathname` matches the `href` of the link: app/components/links.tsx TypeScript JavaScriptTypeScript 'use client' import { usePathname } from 'next/navigation' import Link from 'next/link' export function Links() { const pathname = usePathname() return ( <nav> <ul> <li> <Link className={`link ${pathname === '/' ? 'active' : ''}`} href="/"> Home </Link> </li> <li> <Link className={`link ${pathname === '/about' ? 'active' : ''}`} href="/about" > About </Link> </li> </ul> </nav> ) } #### [Scrolling to an `id`](#scrolling-to-an-id) The default behavior of the Next.js App Router is to **scroll to the top of a new route or to maintain the scroll position for backwards and forwards navigation.** 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>` element. <Link href="/dashboard#settings">Settings</Link> // Output <a href="/dashboard#settings">Settings</a> > **Good to know**: > > * Next.js will scroll to the [Page](/docs/app/building-your-application/routing/pages-and-layouts#pages) if it is not visible in the viewport upon navigation. #### [Disabling scroll restoration](#disabling-scroll-restoration) The default behavior of the Next.js App Router is to **scroll to the top of a new route or to maintain the scroll position for backwards and forwards navigation.** If you'd like to disable this behavior, you can pass `scroll={false}` to the `<Link>` component, or `scroll: false` to `router.push()` or `router.replace()`. // next/link <Link href="/dashboard" scroll={false}> Dashboard </Link> // useRouter import { useRouter } from 'next/navigation' const router = useRouter() router.push('/dashboard', { scroll: false }) [`useRouter()` hook](#userouter-hook) ------------------------------------- The `useRouter` hook allows you to programmatically change routes from [Client Components](/docs/app/building-your-application/rendering/client-components). app/page.js 'use client' import { useRouter } from 'next/navigation' export default function Page() { const router = useRouter() return ( <button type="button" onClick={() => router.push('/dashboard')}> Dashboard </button> ) } For a full list of `useRouter` methods, see the [API reference](/docs/app/api-reference/functions/use-router). > **Recommendation:** Use the `<Link>` component to navigate between routes unless you have a specific requirement for using `useRouter`. [`redirect` function](#redirect-function) ----------------------------------------- For [Server Components](/docs/app/building-your-application/rendering/server-components), use the `redirect` function instead. app/team/\[id\]/page.tsx TypeScript JavaScriptTypeScript import { redirect } from 'next/navigation' async function fetchTeam(id: string) { const res = await fetch('https://...') if (!res.ok) return undefined return res.json() } export default async function Profile({ params }: { params: { id: string } }) { const team = await fetchTeam(params.id) if (!team) { redirect('/login') } // ... } > **Good to know**: > > * `redirect` returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request. > * `redirect` internally throws an error so it should be called outside of `try/catch` blocks. > * `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](#userouter-hook) instead. > * `redirect` also accepts absolute URLs and can be used to redirect to external links. > * If you'd like to redirect before the render process, use [`next.config.js`](/docs/app/building-your-application/routing/redirecting#redirects-in-nextconfigjs) or [Middleware](/docs/app/building-your-application/routing/redirecting#nextresponseredirect-in-middleware). See the [`redirect` API reference](/docs/app/api-reference/functions/redirect) for more information. [Using the native History API](#using-the-native-history-api) ------------------------------------------------------------- Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page. `pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). ### [`window.history.pushState`](#windowhistorypushstate) Use it to add a new entry to the browser's history stack. The user can navigate back to the previous state. For example, to sort a list of products: 'use client' import { useSearchParams } from 'next/navigation' export default function SortProducts() { const searchParams = useSearchParams() function updateSorting(sortOrder: string) { const params = new URLSearchParams(searchParams.toString()) params.set('sort', sortOrder) window.history.pushState(null, '', `?${params.toString()}`) } return ( <> <button onClick={() => updateSorting('asc')}>Sort Ascending</button> <button onClick={() => updateSorting('desc')}>Sort Descending</button> </> ) } ### [`window.history.replaceState`](#windowhistoryreplacestate) Use it to replace the current entry on the browser's history stack. The user is not able to navigate back to the previous state. For example, to switch the application's locale: 'use client' import { usePathname } from 'next/navigation' export function LocaleSwitcher() { const pathname = usePathname() function switchLocale(locale: string) { // e.g. '/en/about' or '/fr/contact' const newPath = `/${locale}${pathname}` window.history.replaceState(null, '', newPath) } return ( <> <button onClick={() => switchLocale('en')}>English</button> <button onClick={() => switchLocale('fr')}>French</button> </> ) } [How Routing and Navigation Works](#how-routing-and-navigation-works) --------------------------------------------------------------------- The App Router uses a hybrid approach for routing and navigation. On the server, your application code is automatically [code-split](#1-code-splitting) by route segments. And on the client, Next.js [prefetches](#2-prefetching) and [caches](#3-caching) the route segments. This means, when a user navigates to a new route, the browser doesn't reload the page, and only the route segments that change re-render - improving the navigation experience and performance. ### [1\. Code Splitting](#1-code-splitting) Code splitting allows you to split your application code into smaller bundles to be downloaded and executed by the browser. This reduces the amount of data transferred and execution time for each request, leading to improved performance. [Server Components](/docs/app/building-your-application/rendering/server-components) allow your application code to be automatically code-split by route segments. This means only the code needed for the current route is loaded on navigation. ### [2\. Prefetching](#2-prefetching) Prefetching is a way to preload a route in the background before the user visits it. There are two ways routes are prefetched in Next.js: * **`<Link>` component**: Routes are automatically prefetched as they become visible in the user's viewport. Prefetching happens when the page first loads or when it comes into view through scrolling. * **`router.prefetch()`**: The `useRouter` hook can be used to prefetch routes programmatically. The `<Link>`'s default prefetching behavior (i.e. when the `prefetch` prop is left unspecified or set to `null`) is different depending on your usage of [`loading.js`](/docs/app/api-reference/file-conventions/loading). Only the shared layout, down the rendered "tree" of components until the first `loading.js` file, is prefetched and cached for `30s`. This reduces the cost of fetching an entire dynamic route, and it means you can show an [instant loading state](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) for better visual feedback to users. You can disable prefetching by setting the `prefetch` prop to `false`. Alternatively, you can prefetch the full page data beyond the loading boundaries by setting the `prefetch` prop to `true`. See the [`<Link>` API reference](/docs/app/api-reference/components/link) for more information. > **Good to know**: > > * Prefetching is not enabled in development, only in production. ### [3\. Caching](#3-caching) Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/building-your-application/caching#router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache. This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred. Learn more about how the [Router Cache](/docs/app/building-your-application/caching#router-cache) works and how to configure it. ### [4\. Partial Rendering](#4-partial-rendering) Partial rendering means only the route segments that change on navigation re-render on the client, and any shared segments are preserved. For example, when navigating between two sibling routes, `/dashboard/settings` and `/dashboard/analytics`, the `settings` and `analytics` pages will be rendered, and the shared `dashboard` layout will be preserved. ![How partial rendering works](/_next/image?url=%2Fdocs%2Flight%2Fpartial-rendering.png&w=3840&q=75)![How partial rendering works](/_next/image?url=%2Fdocs%2Fdark%2Fpartial-rendering.png&w=3840&q=75) Without partial rendering, each navigation would cause the full page to re-render on the client. Rendering only the segment that changes reduces the amount of data transferred and execution time, leading to improved performance. ### [5\. Soft Navigation](#5-soft-navigation) Browsers perform a "hard navigation" when navigating between pages. The Next.js App Router enables "soft navigation" between pages, ensuring only the route segments that have changed are re-rendered (partial rendering). This enables client React state to be preserved during navigation. ### [6\. Back and Forward Navigation](#6-back-and-forward-navigation) By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/building-your-application/caching#router-cache). ### [7\. Routing between `pages/` and `app/`](#7-routing-between-pages-and-app) When incrementally migrating from `pages/` to `app/`, the Next.js router will automatically handle hard navigation between the two. To detect transitions from `pages/` to `app/`, there is a client router filter that leverages probabilistic checking of app routes, which can occasionally result in false positives. By default, such occurrences should be very rare, as we configure the false positive likelihood to be 0.01%. This likelihood can be customized via the `experimental.clientRouterFilterAllowedRate` option in `next.config.js`. It's important to note that lowering the false positive rate will increase the size of the generated filter in the client bundle. Alternatively, if you prefer to disable this handling completely and manage the routing between `pages/` and `app/` manually, you can set `experimental.clientRouterFilter` to false in `next.config.js`. When this feature is disabled, any dynamic routes in pages that overlap with app routes won't be navigated to properly by default. Next Steps ---------- [ App Router Building Your Application ### Caching An overview of caching mechanisms in Next.js. ](/docs/app/building-your-application/caching)[ App Router ... Configuring ### TypeScript Next.js provides a TypeScript-first development experience for building your React application. ](/docs/app/building-your-application/configuring/typescript) [Previous Pages and Layouts ](/docs/app/building-your-application/routing/pages-and-layouts) [Next Loading UI and Streaming ](/docs/app/building-your-application/routing/loading-ui-and-streaming) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"122f3af1133c002c2665bd7dcd922ace\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/generate-viewport
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [ generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [The viewport object](#the-viewport-object) * [generateViewport function](#generateviewport-function) * [Viewport Fields](#viewport-fields) * [themeColor](#themecolor) * [width, initialScale, maximumScale and userScalable](#width-initialscale-maximumscale-and-userscalable) * [colorScheme](#colorscheme) * [Types](#types) * [viewport object](#viewport-object) * [generateViewport function](#generateviewport-function-1) * [Regular function](#regular-function) * [With segment props](#with-segment-props) * [JavaScript Projects](#javascript-projects) * [Version History](#version-history) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/generate-viewport.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)generateViewport generateViewport ================ You can customize the initial viewport of the page with the static `viewport` object or the dynamic `generateViewport` function. > **Good to know**: > > * The `viewport` object and `generateViewport` function exports are **only supported in Server Components**. > * You cannot export both the `viewport` object and `generateViewport` function from the same route segment. > * If you're coming from migrating `metadata` exports, you can use [metadata-to-viewport-export codemod](/docs/app/building-your-application/upgrading/codemods#metadata-to-viewport-export) to update your changes. [The `viewport` object](#the-viewport-object) --------------------------------------------- To define the viewport options, export a `viewport` object from a `layout.jsx` or `page.jsx` file. layout.tsx | page.tsx TypeScript JavaScriptTypeScript import type { Viewport } from 'next' export const viewport: Viewport = { themeColor: 'black', } export default function Page() {} [`generateViewport` function](#generateviewport-function) --------------------------------------------------------- `generateViewport` should return a [`Viewport` object](#viewport-fields) containing one or more viewport fields. layout.tsx | page.tsx TypeScript JavaScriptTypeScript export function generateViewport({ params }) { return { themeColor: '...', } } > **Good to know**: > > * If the viewport doesn't depend on runtime information, it should be defined using the static [`viewport` object](#the-viewport-object) rather than `generateMetadata`. [Viewport Fields](#viewport-fields) ----------------------------------- ### [`themeColor`](#themecolor) Learn more about [`theme-color`](https://developer.mozilla.org/docs/Web/HTML/Element/meta/name/theme-color). **Simple theme color** layout.tsx | page.tsx TypeScript JavaScriptTypeScript import type { Viewport } from 'next' export const viewport: Viewport = { themeColor: 'black', } <head> output <meta name="theme-color" content="black" /> **With media attribute** layout.tsx | page.tsx TypeScript JavaScriptTypeScript import type { Viewport } from 'next' export const viewport: Viewport = { themeColor: [ { media: '(prefers-color-scheme: light)', color: 'cyan' }, { media: '(prefers-color-scheme: dark)', color: 'black' }, ], } <head> output <meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" /> <meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" /> ### [`width`, `initialScale`, `maximumScale` and `userScalable`](#width-initialscale-maximumscale-and-userscalable) > **Good to know**: The `viewport` meta tag is automatically set, and manual configuration is usually unnecessary as the default is sufficient. However, the information is provided for completeness. layout.tsx | page.tsx TypeScript JavaScriptTypeScript import type { Viewport } from 'next' export const viewport: Viewport = { width: 'device-width', initialScale: 1, maximumScale: 1, userScalable: false, // Also supported by less commonly used // interactiveWidget: 'resizes-visual', } <head> output <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> ### [`colorScheme`](#colorscheme) Learn more about [`color-scheme`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name#:~:text=color%2Dscheme%3A%20specifies,of%20the%20following%3A). layout.tsx | page.tsx TypeScript JavaScriptTypeScript import type { Viewport } from 'next' export const viewport: Viewport = { colorScheme: 'dark', } <head> output <meta name="color-scheme" content="dark" /> [Types](#types) --------------- You can add type safety to your viewport object by using the `Viewport` type. If you are using the [built-in TypeScript plugin](/docs/app/building-your-application/configuring/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want. ### [`viewport` object](#viewport-object) import type { Viewport } from 'next' export const viewport: Viewport = { themeColor: 'black', } ### [`generateViewport` function](#generateviewport-function-1) #### [Regular function](#regular-function) import type { Viewport } from 'next' export function generateViewport(): Viewport { return { themeColor: 'black', } } #### [With segment props](#with-segment-props) import type { Viewport } from 'next' type Props = { params: { id: string } searchParams: { [key: string]: string | string[] | undefined } } export function generateViewport({ params, searchParams }: Props): Viewport { return { themeColor: 'black', } } export default function Page({ params, searchParams }: Props) {} #### [JavaScript Projects](#javascript-projects) For JavaScript projects, you can use JSDoc to add type safety. /** @type {import("next").Viewport} */ export const viewport = { themeColor: 'black', } [Version History](#version-history) ----------------------------------- Version Changes `v14.0.0` `viewport` and `generateViewport` introduced. Next Steps ---------- View all the Metadata API options. [ App Router ... File Conventions ### Metadata Files API documentation for the metadata file conventions. ](/docs/app/api-reference/file-conventions/metadata)[ App Router ... Optimizing ### Metadata Use the Metadata API to define metadata in any layout or page. ](/docs/app/building-your-application/optimizing/metadata) [Previous generateStaticParams ](/docs/app/api-reference/functions/generate-static-params) [Next headers ](/docs/app/api-reference/functions/headers) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"70c1923b543b7caf7114b55820fcbe1c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)API Reference API Reference ============= The Next.js API reference is divided into the following sections: [ ### Components API Reference for Next.js built-in components. ](/docs/app/api-reference/components)[ ### File Conventions API Reference for Next.js Special Files. ](/docs/app/api-reference/file-conventions)[ ### Functions API Reference for Next.js Functions and Hooks. ](/docs/app/api-reference/functions)[ ### next.config.js Options Learn how to configure your application with next.config.js. ](/docs/app/api-reference/next-config-js)[ ### create-next-app Create Next.js apps in one command with create-next-app. ](/docs/app/api-reference/create-next-app)[ ### Edge Runtime API Reference for the Edge Runtime. ](/docs/app/api-reference/edge)[ ### Next.js CLI Learn how the Next.js CLI allows you to develop, build, and start your application, and more. ](/docs/app/api-reference/next-cli) [Previous Migrating from Create React App ](/docs/app/building-your-application/upgrading/from-create-react-app) [Next Components ](/docs/app/api-reference/components) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"c605c1ca916fd104964b4a6b18f43df0\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/components
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/01-components/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[API Reference](/docs/app/api-reference)Components Components ========== [ ### Font Optimizing loading web fonts with the built-in \`next/font\` loaders. ](/docs/app/api-reference/components/font)[ ### <Image> Optimize Images in your Next.js Application using the built-in \`next/image\` Component. ](/docs/app/api-reference/components/image)[ ### <Link> Enable fast client-side navigation with the built-in \`next/link\` component. ](/docs/app/api-reference/components/link)[ ### <Script> Optimize third-party scripts in your Next.js application using the built-in \`next/script\` Component. ](/docs/app/api-reference/components/script) [Previous API Reference ](/docs/app/api-reference) [Next Font ](/docs/app/api-reference/components/font) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e1e3addf2b3377140798d47b2b75faa2\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [ Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Instant Loading States](#instant-loading-states) * [Streaming with Suspense](#streaming-with-suspense) * [What is Streaming?](#what-is-streaming) * [Example](#example) * [SEO](#seo) * [Status Codes](#status-codes) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/04-loading-ui-and-streaming.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Loading UI and Streaming Loading UI and Streaming ======================== The special file `loading.js` helps you create meaningful Loading UI with [React Suspense](https://react.dev/reference/react/Suspense). With this convention, you can show an [instant loading state](#instant-loading-states) from the server while the content of a route segment loads. The new content is automatically swapped in once rendering is complete. ![Loading UI](/_next/image?url=%2Fdocs%2Flight%2Floading-ui.png&w=3840&q=75)![Loading UI](/_next/image?url=%2Fdocs%2Fdark%2Floading-ui.png&w=3840&q=75) [Instant Loading States](#instant-loading-states) ------------------------------------------------- An instant loading state is fallback UI that is shown immediately upon navigation. You can pre-render loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience. Create a loading state by adding a `loading.js` file inside a folder. ![loading.js special file](/_next/image?url=%2Fdocs%2Flight%2Floading-special-file.png&w=3840&q=75)![loading.js special file](/_next/image?url=%2Fdocs%2Fdark%2Floading-special-file.png&w=3840&q=75) app/dashboard/loading.tsx TypeScript JavaScriptTypeScript export default function Loading() { // You can add any UI inside Loading, including a Skeleton. return <LoadingSkeleton /> } In the same folder, `loading.js` will be nested inside `layout.js`. It will automatically wrap the `page.js` file and any children below in a `<Suspense>` boundary. ![loading.js overview](/_next/image?url=%2Fdocs%2Flight%2Floading-overview.png&w=3840&q=75)![loading.js overview](/_next/image?url=%2Fdocs%2Fdark%2Floading-overview.png&w=3840&q=75) > **Good to know**: > > * Navigation is immediate, even with [server-centric routing](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). > * Navigation is interruptible, meaning changing routes does not need to wait for the content of the route to fully load before navigating to another route. > * Shared layouts remain interactive while new route segments load. > **Recommendation:** Use the `loading.js` convention for route segments (layouts and pages) as Next.js optimizes this functionality. [Streaming with Suspense](#streaming-with-suspense) --------------------------------------------------- In addition to `loading.js`, you can also manually create Suspense Boundaries for your own UI components. The App Router supports streaming with [Suspense](https://react.dev/reference/react/Suspense) for both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). > **Good to know**: > > * [Some browsers](https://bugs.webkit.org/show_bug.cgi?id=252413) buffer a streaming response. You may not see the streamed response until the exceeds 1024 bytes. This typically only affects “hello world” applications, but not real applications. ### [What is Streaming?](#what-is-streaming) To learn how Streaming works in React and Next.js, it's helpful to understand **Server-Side Rendering (SSR)** and its limitations. With SSR, there's a series of steps that need to be completed before a user can see and interact with a page: 1. First, all data for a given page is fetched on the server. 2. The server then renders the HTML for the page. 3. The HTML, CSS, and JavaScript for the page are sent to the client. 4. A non-interactive user interface is shown using the generated HTML, and CSS. 5. Finally, React [hydrates](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) the user interface to make it interactive. ![Chart showing Server Rendering without Streaming](/_next/image?url=%2Fdocs%2Flight%2Fserver-rendering-without-streaming-chart.png&w=3840&q=75)![Chart showing Server Rendering without Streaming](/_next/image?url=%2Fdocs%2Fdark%2Fserver-rendering-without-streaming-chart.png&w=3840&q=75) These steps are sequential and blocking, meaning the server can only render the HTML for a page once all the data has been fetched. And, on the client, React can only hydrate the UI once the code for all components in the page has been downloaded. SSR with React and Next.js helps improve the perceived loading performance by showing a non-interactive page to the user as soon as possible. ![Server Rendering without Streaming](/_next/image?url=%2Fdocs%2Flight%2Fserver-rendering-without-streaming.png&w=3840&q=75)![Server Rendering without Streaming](/_next/image?url=%2Fdocs%2Fdark%2Fserver-rendering-without-streaming.png&w=3840&q=75) However, it can still be slow as all data fetching on server needs to be completed before the page can be shown to the user. **Streaming** allows you to break down the page's HTML into smaller chunks and progressively send those chunks from the server to the client. ![How Server Rendering with Streaming Works](/_next/image?url=%2Fdocs%2Flight%2Fserver-rendering-with-streaming.png&w=3840&q=75)![How Server Rendering with Streaming Works](/_next/image?url=%2Fdocs%2Fdark%2Fserver-rendering-with-streaming.png&w=3840&q=75) This enables parts of the page to be displayed sooner, without waiting for all the data to load before any UI can be rendered. Streaming works well with React's component model because each component can be considered a chunk. Components that have higher priority (e.g. product information) or that don't rely on data can be sent first (e.g. layout), and React can start hydration earlier. Components that have lower priority (e.g. reviews, related products) can be sent in the same server request after their data has been fetched. ![Chart showing Server Rendering with Streaming](/_next/image?url=%2Fdocs%2Flight%2Fserver-rendering-with-streaming-chart.png&w=3840&q=75)![Chart showing Server Rendering with Streaming](/_next/image?url=%2Fdocs%2Fdark%2Fserver-rendering-with-streaming-chart.png&w=3840&q=75) Streaming is particularly beneficial when you want to prevent long data requests from blocking the page from rendering as it can reduce the [Time To First Byte (TTFB)](https://web.dev/ttfb/) and [First Contentful Paint (FCP)](https://web.dev/first-contentful-paint/). It also helps improve [Time to Interactive (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/), especially on slower devices. ### [Example](#example) `<Suspense>` works by wrapping a component that performs an asynchronous action (e.g. fetch data), showing fallback UI (e.g. skeleton, spinner) while it's happening, and then swapping in your component once the action completes. app/dashboard/page.tsx TypeScript JavaScriptTypeScript import { Suspense } from 'react' import { PostFeed, Weather } from './Components' export default function Posts() { return ( <section> <Suspense fallback={<p>Loading feed...</p>}> <PostFeed /> </Suspense> <Suspense fallback={<p>Loading weather...</p>}> <Weather /> </Suspense> </section> ) } By using Suspense, you get the benefits of: 1. **Streaming Server Rendering** - Progressively rendering HTML from the server to the client. 2. **Selective Hydration** - React prioritizes what components to make interactive first based on user interaction. For more Suspense examples and use cases, please see the [React Documentation](https://react.dev/reference/react/Suspense). ### [SEO](#seo) * Next.js will wait for data fetching inside [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) to complete before streaming UI to the client. This guarantees the first part of a streamed response includes `<head>` tags. * Since streaming is server-rendered, it does not impact SEO. You can use the [Rich Results Test](https://search.google.com/test/rich-results) tool from Google to see how your page appears to Google's web crawlers and view the serialized HTML ([source](https://web.dev/rendering-on-the-web/#seo-considerations)). ### [Status Codes](#status-codes) When streaming, a `200` status code will be returned to signal that the request was successful. The server can still communicate errors or issues to the client within the streamed content itself, for example, when using [`redirect`](/docs/app/api-reference/functions/redirect) or [`notFound`](/docs/app/api-reference/functions/not-found). Since the response headers have already been sent to the client, the status code of the response cannot be updated. This does not affect SEO. [Previous Linking and Navigating ](/docs/app/building-your-application/routing/linking-and-navigating) [Next Error Handling ](/docs/app/building-your-application/routing/error-handling) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"ed951708083a658c26ce5d764c84e504\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/memory-usage
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [ Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Reduce number of dependencies](#reduce-number-of-dependencies) * [Run next build with --experimental-debug-memory-usage](#run-next-build-with---experimental-debug-memory-usage) * [Record a heap profile](#record-a-heap-profile) * [Analyze a snapshot of the heap](#analyze-a-snapshot-of-the-heap) * [Webpack build worker](#webpack-build-worker) * [Disable Webpack cache](#disable-webpack-cache) * [Disable source maps](#disable-source-maps) * [Edge memory issues](#edge-memory-issues) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/13-memory-usage.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Memory Usage Memory Usage ============ As applications grow and become more feature rich, they can demand more resources when developing locally or creating production builds. Let's explore some strategies and techniques to optimize memory and address common memory issues in Next.js. [Reduce number of dependencies](#reduce-number-of-dependencies) --------------------------------------------------------------- Applications with a large amount of dependencies will use more memory. The [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) can help you investigate large dependencies in your application that may be able to be removed to improve performance and memory usage. [Run `next build` with `--experimental-debug-memory-usage`](#run-next-build-with---experimental-debug-memory-usage) ------------------------------------------------------------------------------------------------------------------- Starting in `14.2.0`, you can run `next build --experimental-debug-memory-usage` to run the build in a mode where Next.js will print out information about memory usage continuously throughout the build, such as heap usage and garbage collection statistics. Heap snapshots will also be taken automatically when memory usage gets close to the configured limit. > **Good to know**: This feature is not compatible with the Webpack build worker option which is auto-enabled unless you have custom webpack config. [Record a heap profile](#record-a-heap-profile) ----------------------------------------------- To look for memory issues, you can record a heap profile from Node.js and load it in Chrome DevTools to identify potential sources of memory leaks. In your terminal, pass the `--heap-prof` flag to Node.js when starting your Next.js build: node --heap-prof node_modules/next/dist/bin/next build At the end of the build, a `.heapprofile` file will be created by Node.js. In Chrome DevTools, you can open the Memory tab and click on the "Load Profile" button to visualize the file. [Analyze a snapshot of the heap](#analyze-a-snapshot-of-the-heap) ----------------------------------------------------------------- You can use an inspector tool to analyze the memory usage of the application. When running the `next build` or `next dev` command, add `NODE_OPTIONS=--inspect` to the beginning of the command. This will expose the inspector agent on the default port. If you wish to break before any user code starts, you can pass `--inspect-brk` instead. While the process is running, you can use a tool such as Chrome DevTools to connect to the debugging port to record and analyze a snapshot of the heap to see what memory is being retained. Starting in `14.2.0`, you can also run `next build` with the `--experimental-debug-memory-usage` flag to make it easier to take heap snapshots. While running in this mode, you can send a `SIGUSR2` signal to the process at any point, and the process will take a heap snapshot. The heap snapshot will be saved to the project root of the Next.js application and can be loaded in any heap analyzer, such as Chrome DevTools, to see what memory is retained. This mode is not yet compatible with Webpack build workers. See [how to record and analyze heap snapshots](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots) for more information. [Webpack build worker](#webpack-build-worker) --------------------------------------------- The Webpack build worker allows you to run Webpack compilations inside a separate Node.js worker which will decrease memory usage of your application during builds. This option is enabled by default if your application does not have a custom Webpack configuration starting in `v14.1.0`. If you are using an older version of Next.js or you have a custom Webpack configuration, you can enable this option by setting `experimental.webpackBuildWorker: true` inside your `next.config.js`. > **Good to know**: This feature may not be compatible with all custom Webpack plugins. [Disable Webpack cache](#disable-webpack-cache) ----------------------------------------------- The [Webpack cache](https://webpack.js.org/configuration/cache/) saves generated Webpack modules in memory and/or to disk to improve the speed of builds. This can help with performance, but it will also increase the memory usage of your application to store the cached data. You can disable this behavior by adding a [custom Webpack configuration](/docs/app/api-reference/next-config-js/webpack) to your application: next.config.mjs /** @type {import('next').NextConfig} */ const nextConfig = { webpack: ( config, { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack } ) => { if (cfg.cache && !dev) { cfg.cache = Object.freeze({ type: 'memory', }) cfg.cache.maxMemoryGenerations = 0 } // Important: return the modified config return config }, } export default nextConfig [Disable source maps](#disable-source-maps) ------------------------------------------- Generating source maps consumes extra memory during the build process. You can disable source map generation by adding `productionBrowserSourceMaps: false` and `experimental.serverSourceMaps: false` to your Next.js configuration. > **Good to know**: Some plugins may turn on source maps and may require custom configuration to disable. [Edge memory issues](#edge-memory-issues) ----------------------------------------- Next.js `v14.1.3` fixed a memory issue when using the Edge runtime. Please update to this version (or later) to see if it addresses your issue. [Previous Third Party Libraries ](/docs/app/building-your-application/optimizing/third-party-libraries) [Next Configuring ](/docs/app/building-your-application/configuring) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"f23f73e27b33e3b2d0bdb690835f1a90\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/headers
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [ headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [headers()](#headers) * [API Reference](#api-reference) * [Parameters](#parameters) * [Returns](#returns) * [Examples](#examples) * [Usage with Data Fetching](#usage-with-data-fetching) * [IP Address](#ip-address) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/headers.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)headers headers ======= The `headers` function allows you to read the HTTP incoming request headers from a [Server Component](/docs/app/building-your-application/rendering/server-components). [`headers()`](#headers) ----------------------- This API extends the [Web Headers API](https://developer.mozilla.org/docs/Web/API/Headers). It is **read-only**, meaning you cannot `set` / `delete` the outgoing request headers. app/page.tsx TypeScript JavaScriptTypeScript import { headers } from 'next/headers' export default function Page() { const headersList = headers() const referer = headersList.get('referer') return <div>Referer: {referer}</div> } > **Good to know**: > > * `headers()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering)** at request time. ### [API Reference](#api-reference) const headersList = headers() #### [Parameters](#parameters) `headers` does not take any parameters. #### [Returns](#returns) `headers` returns a **read-only** [Web Headers](https://developer.mozilla.org/docs/Web/API/Headers) object. * [`Headers.entries()`](https://developer.mozilla.org/docs/Web/API/Headers/entries): Returns an [`iterator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all key/value pairs contained in this object. * [`Headers.forEach()`](https://developer.mozilla.org/docs/Web/API/Headers/forEach): Executes a provided function once for each key/value pair in this `Headers` object. * [`Headers.get()`](https://developer.mozilla.org/docs/Web/API/Headers/get): Returns a [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) sequence of all the values of a header within a `Headers` object with a given name. * [`Headers.has()`](https://developer.mozilla.org/docs/Web/API/Headers/has): Returns a boolean stating whether a `Headers` object contains a certain header. * [`Headers.keys()`](https://developer.mozilla.org/docs/Web/API/Headers/keys): Returns an [`iterator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) allowing you to go through all keys of the key/value pairs contained in this object. * [`Headers.values()`](https://developer.mozilla.org/docs/Web/API/Headers/values): Returns an [`iterator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) allowing you to go through all values of the key/value pairs contained in this object. ### [Examples](#examples) #### [Usage with Data Fetching](#usage-with-data-fetching) `headers()` can be used in combination with [Suspense for Data Fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating). app/page.js import { Suspense } from 'react' import { headers } from 'next/headers' async function User() { const authorization = headers().get('authorization') const res = await fetch('...', { headers: { authorization }, // Forward the authorization header }) const user = await res.json() return <h1>{user.name}</h1> } export default function Page() { return ( <Suspense fallback={null}> <User /> </Suspense> ) } #### [IP Address](#ip-address) `headers()` can be used to get the IP address of the client. app/page.js import { Suspense } from 'react' import { headers } from 'next/headers' function IP() { const FALLBACK_IP_ADDRESS = '0.0.0.0' const forwardedFor = headers().get('x-forwarded-for') if (forwardedFor) { return forwardedFor.split(',')[0] ?? FALLBACK_IP_ADDRESS } return headers().get('x-real-ip') ?? FALLBACK_IP_ADDRESS } export default function Page() { return ( <Suspense fallback={null}> <IP /> </Suspense> ) } In addition to `x-forwarded-for`, `headers()` can also read: * `x-real-ip` * `x-forwarded-host` * `x-forwarded-port` * `x-forwarded-proto` [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `headers` introduced. [Previous generateViewport ](/docs/app/api-reference/functions/generate-viewport) [Next ImageResponse ](/docs/app/api-reference/functions/image-response) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"bd6001057b060ffb35044dd60916cd5c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [ CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Configuring CSS-in-JS in app](#configuring-css-in-js-in-app) * [styled-jsx](#styled-jsx) * [Styled Components](#styled-components) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/05-styling/03-css-in-js.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Styling](/docs/app/building-your-application/styling)CSS-in-JS CSS-in-JS ========= > **Warning:** CSS-in-JS libraries which require runtime JavaScript are not currently supported in Server Components. Using CSS-in-JS with newer React features like Server Components and Streaming requires library authors to support the latest version of React, including [concurrent rendering](https://react.dev/blog/2022/03/29/react-v18#what-is-concurrent-react). > > We're working with the React team on upstream APIs to handle CSS and JavaScript assets with support for React Server Components and streaming architecture. The following libraries are supported in Client Components in the `app` directory (alphabetical): * [`chakra-ui`](https://chakra-ui.com/getting-started/nextjs-app-guide) * [`kuma-ui`](https://kuma-ui.com) * [`@mui/material`](https://mui.com/material-ui/guides/next-js-app-router/) * [`@mui/joy`](https://mui.com/joy-ui/integrations/next-js-app-router/) * [`pandacss`](https://panda-css.com) * [`styled-jsx`](#styled-jsx) * [`styled-components`](#styled-components) * [`stylex`](https://stylexjs.com) * [`tamagui`](https://tamagui.dev/docs/guides/next-js#server-components) * [`tss-react`](https://tss-react.dev/) * [`vanilla-extract`](https://vanilla-extract.style) The following are currently working on support: * [`emotion`](https://github.com/emotion-js/emotion/issues/2928) > **Good to know**: We're testing out different CSS-in-JS libraries and we'll be adding more examples for libraries that support React 18 features and/or the `app` directory. If you want to style Server Components, we recommend using [CSS Modules](/docs/app/building-your-application/styling/css-modules) or other solutions that output CSS files, like PostCSS or [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css). [Configuring CSS-in-JS in `app`](#configuring-css-in-js-in-app) --------------------------------------------------------------- Configuring CSS-in-JS is a three-step opt-in process that involves: 1. A **style registry** to collect all CSS rules in a render. 2. The new `useServerInsertedHTML` hook to inject rules before any content that might use them. 3. A Client Component that wraps your app with the style registry during initial server-side rendering. ### [`styled-jsx`](#styled-jsx) Using `styled-jsx` in Client Components requires using `v5.1.0`. First, create a new registry: app/registry.tsx TypeScript JavaScriptTypeScript 'use client' import React, { useState } from 'react' import { useServerInsertedHTML } from 'next/navigation' import { StyleRegistry, createStyleRegistry } from 'styled-jsx' export default function StyledJsxRegistry({ children, }: { children: React.ReactNode }) { // Only create stylesheet once with lazy initial state // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state const [jsxStyleRegistry] = useState(() => createStyleRegistry()) useServerInsertedHTML(() => { const styles = jsxStyleRegistry.styles() jsxStyleRegistry.flush() return <>{styles}</> }) return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry> } Then, wrap your [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) with the registry: app/layout.tsx TypeScript JavaScriptTypeScript import StyledJsxRegistry from './registry' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html> <body> <StyledJsxRegistry>{children}</StyledJsxRegistry> </body> </html> ) } [View an example here](https://github.com/vercel/app-playground/tree/main/app/styling/styled-jsx). ### [Styled Components](#styled-components) Below is an example of how to configure `styled-components@6` or newer: First, enable styled-components in `next.config.js`. next.config.js module.exports = { compiler: { styledComponents: true, }, } Then, use the `styled-components` API to create a global registry component to collect all CSS style rules generated during a render, and a function to return those rules. Then use the `useServerInsertedHTML` hook to inject the styles collected in the registry into the `<head>` HTML tag in the root layout. lib/registry.tsx TypeScript JavaScriptTypeScript 'use client' import React, { useState } from 'react' import { useServerInsertedHTML } from 'next/navigation' import { ServerStyleSheet, StyleSheetManager } from 'styled-components' export default function StyledComponentsRegistry({ children, }: { children: React.ReactNode }) { // Only create stylesheet once with lazy initial state // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet()) useServerInsertedHTML(() => { const styles = styledComponentsStyleSheet.getStyleElement() styledComponentsStyleSheet.instance.clearTag() return <>{styles}</> }) if (typeof window !== 'undefined') return <>{children}</> return ( <StyleSheetManager sheet={styledComponentsStyleSheet.instance}> {children} </StyleSheetManager> ) } Wrap the `children` of the root layout with the style registry component: app/layout.tsx TypeScript JavaScriptTypeScript import StyledComponentsRegistry from './lib/registry' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html> <body> <StyledComponentsRegistry>{children}</StyledComponentsRegistry> </body> </html> ) } [View an example here](https://github.com/vercel/app-playground/tree/main/app/styling/styled-components). > **Good to know**: > > * During server rendering, styles will be extracted to a global registry and flushed to the `<head>` of your HTML. This ensures the style rules are placed before any content that might use them. In the future, we may use an upcoming React feature to determine where to inject the styles. > * During streaming, styles from each chunk will be collected and appended to existing styles. After client-side hydration is complete, `styled-components` will take over as usual and inject any further dynamic styles. > * We specifically use a Client Component at the top level of the tree for the style registry because it's more efficient to extract CSS rules this way. It avoids re-generating styles on subsequent server renders, and prevents them from being sent in the Server Component payload. > * For advanced use cases where you need to configure individual properties of styled-components compilation, you can read our [Next.js styled-components API reference](/docs/architecture/nextjs-compiler#styled-components) to learn more. [Previous Tailwind CSS ](/docs/app/building-your-application/styling/tailwind-css) [Next Sass ](/docs/app/building-your-application/styling/sass) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"37f475e26c0abf0621e1127bdde95896\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/styling/sass
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [ Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Customizing Sass Options](#customizing-sass-options) * [Sass Variables](#sass-variables) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/05-styling/04-sass.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Styling](/docs/app/building-your-application/styling)Sass Sass ==== Next.js has built-in support for integrating with Sass after the package is installed using both the `.scss` and `.sass` extensions. You can use component-level Sass via CSS Modules and the `.module.scss`or `.module.sass` extension. First, install [`sass`](https://github.com/sass/sass): Terminal npm install --save-dev sass > **Good to know**: > > Sass supports [two different syntaxes](https://sass-lang.com/documentation/syntax), each with their own extension. The `.scss` extension requires you use the [SCSS syntax](https://sass-lang.com/documentation/syntax#scss), while the `.sass` extension requires you use the [Indented Syntax ("Sass")](https://sass-lang.com/documentation/syntax#the-indented-syntax). > > If you're not sure which to choose, start with the `.scss` extension which is a superset of CSS, and doesn't require you learn the Indented Syntax ("Sass"). ### [Customizing Sass Options](#customizing-sass-options) If you want to configure the Sass compiler, use `sassOptions` in `next.config.js`. next.config.js const path = require('path') module.exports = { sassOptions: { includePaths: [path.join(__dirname, 'styles')], }, } ### [Sass Variables](#sass-variables) Next.js supports Sass variables exported from CSS Module files. For example, using the exported `primaryColor` Sass variable: app/variables.module.scss $primary-color: #64ff00; :export { primaryColor: $primary-color; } app/page.js // maps to root `/` URL import variables from './variables.module.scss' export default function Page() { return <h1 style={{ color: variables.primaryColor }}>Hello, Next.js!</h1> } [Previous CSS-in-JS ](/docs/app/building-your-application/styling/css-in-js) [Next Optimizing ](/docs/app/building-your-application/optimizing) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"66c53b08023aff9963e16242508d78af\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Configuring Configuring =========== Next.js allows you to customize your project to meet specific requirements. This includes integrations with TypeScript, ESlint, and more, as well as internal configuration options such as Absolute Imports and Environment Variables. [ ### TypeScript Next.js provides a TypeScript-first development experience for building your React application. ](/docs/app/building-your-application/configuring/typescript)[ ### ESLint Next.js provides an integrated ESLint experience by default. These conformance rules help you use Next.js in an optimal way. ](/docs/app/building-your-application/configuring/eslint)[ ### Environment Variables Learn to add and access environment variables in your Next.js application. ](/docs/app/building-your-application/configuring/environment-variables)[ ### Absolute Imports and Module Path Aliases Configure module path aliases that allow you to remap certain import paths. ](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases)[ ### MDX Learn how to configure MDX and use it in your Next.js apps. ](/docs/app/building-your-application/configuring/mdx)[ ### src Directory Save pages under the \`src\` directory as an alternative to the root \`pages\` directory. ](/docs/app/building-your-application/configuring/src-directory)[ ### Draft Mode Next.js has draft mode to toggle between static and dynamic pages. You can learn how it works with App Router here. ](/docs/app/building-your-application/configuring/draft-mode)[ ### Content Security Policy Learn how to set a Content Security Policy (CSP) for your Next.js application. ](/docs/app/building-your-application/configuring/content-security-policy) [Previous Memory Usage ](/docs/app/building-your-application/optimizing/memory-usage) [Next TypeScript ](/docs/app/building-your-application/configuring/typescript) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"1c448c532d3c04810a9bf29b8eb847d4\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/components/font
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [ Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Font Function Arguments](#font-function-arguments) * [src](#src) * [weight](#weight) * [style](#style) * [subsets](#subsets) * [axes](#axes) * [display](#display) * [preload](#preload) * [fallback](#fallback) * [adjustFontFallback](#adjustfontfallback) * [variable](#variable) * [declarations](#declarations) * [Applying Styles](#applying-styles) * [className](#classname) * [style](#style-1) * [CSS Variables](#css-variables) * [Using a font definitions file](#using-a-font-definitions-file) * [Version Changes](#version-changes) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/01-components/font.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Components](/docs/app/api-reference/components)Font Font Module =========== This API reference will help you understand how to use [`next/font/google`](/docs/app/building-your-application/optimizing/fonts#google-fonts) and [`next/font/local`](/docs/app/building-your-application/optimizing/fonts#local-fonts). For features and usage, please see the [Optimizing Fonts](/docs/app/building-your-application/optimizing/fonts) page. ### [Font Function Arguments](#font-function-arguments) For usage, review [Google Fonts](/docs/app/building-your-application/optimizing/fonts#google-fonts) and [Local Fonts](/docs/app/building-your-application/optimizing/fonts#local-fonts). Key `font/google` `font/local` Type Required [`src`](#src) String or Array of Objects Yes [`weight`](#weight) String or Array Required/Optional [`style`](#style) String or Array \- [`subsets`](#subsets) Array of Strings \- [`axes`](#axes) Array of Strings \- [`display`](#display) String \- [`preload`](#preload) Boolean \- [`fallback`](#fallback) Array of Strings \- [`adjustFontFallback`](#adjustfontfallback) Boolean or String \- [`variable`](#variable) String \- [`declarations`](#declarations) Array of Objects \- ### [`src`](#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. Used in `next/font/local` * Required Examples: * `src:'./fonts/my-font.woff2'` where `my-font.woff2` is placed in a directory named `fonts` inside the `app` directory * `src:[{path: './inter/Inter-Thin.ttf', weight: '100',},{path: './inter/Inter-Regular.ttf',weight: '400',},{path: './inter/Inter-Bold-Italic.ttf', weight: '700',style: 'italic',},]` * if the font loader function is called in `app/page.tsx` using `src:'../styles/fonts/my-font.ttf'`, then `my-font.ttf` is placed in `styles/fonts` at the root of the project ### [`weight`](#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 values if it's a [variable](https://fonts.google.com/variablefonts) font * An array of weight values if the font is not a [variable google font](https://fonts.google.com/variablefonts). It applies to `next/font/google` only. Used in `next/font/google` and `next/font/local` * Required if the font being used is **not** [variable](https://fonts.google.com/variablefonts) Examples: * `weight: '400'`: A string for a single weight value - for the font [`Inter`](https://fonts.google.com/specimen/Inter?query=inter), the possible values are `'100'`, `'200'`, `'300'`, `'400'`, `'500'`, `'600'`, `'700'`, `'800'`, `'900'` or `'variable'` where `'variable'` is the default) * `weight: '100 900'`: A string for the range between `100` and `900` for a variable font * `weight: ['100','400','900']`: An array of 3 possible values for a non variable font ### [`style`](#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 default value of `'normal'` * An array of style values if the font is not a [variable google font](https://fonts.google.com/variablefonts). It applies to `next/font/google` only. Used in `next/font/google` and `next/font/local` * Optional Examples: * `style: 'italic'`: A string - it can be `normal` or `italic` for `next/font/google` * `style: 'oblique'`: A string - it can take any value for `next/font/local` but is expected to come from [standard font styles](https://developer.mozilla.org/docs/Web/CSS/font-style) * `style: ['italic','normal']`: An array of 2 values for `next/font/google` - the values are from `normal` and `italic` ### [`subsets`](#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 [preloaded](/docs/app/building-your-application/optimizing/fonts#specifying-a-subset). Fonts specified via `subsets` will have a link preload tag injected into the head when the [`preload`](#preload) option is true, which is the default. Used in `next/font/google` * Optional Examples: * `subsets: ['latin']`: An array with the subset `latin` You can find a list of all subsets on the Google Fonts page for your font. ### [`axes`](#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 `next/font/google` * Optional Examples: * `axes: ['slnt']`: An array with value `slnt` for the `Inter` variable font which has `slnt` as additional `axes` as shown [here](https://fonts.google.com/variablefonts?vfquery=inter#font-families). You can find the possible `axes` values for your font by using the filter on the [Google variable fonts page](https://fonts.google.com/variablefonts#font-families) and looking for axes other than `wght` ### [`display`](#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 `'auto'`, `'block'`, `'swap'`, `'fallback'` or `'optional'` with default value of `'swap'`. Used in `next/font/google` and `next/font/local` * Optional Examples: * `display: 'optional'`: A string assigned to the `optional` value ### [`preload`](#preload) A boolean value that specifies whether the font should be [preloaded](/docs/app/building-your-application/optimizing/fonts#preloading) or not. The default is `true`. Used in `next/font/google` and `next/font/local` * Optional Examples: * `preload: false` ### [`fallback`](#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: ['system-ui', 'arial']`: An array setting the fallback fonts to `system-ui` or `arial` ### [`adjustFontFallback`](#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 `next/font/local`: A string or boolean `false` value that sets whether an automatic fallback font should be used to reduce [Cumulative Layout Shift](https://web.dev/cls/). The possible values are `'Arial'`, `'Times New Roman'` or `false`. The default is `'Arial'`. Used in `next/font/google` and `next/font/local` * Optional Examples: * `adjustFontFallback: false`: for `next/font/google` * `adjustFontFallback: 'Times New Roman'`: for `next/font/local` ### [`variable`](#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` * Optional Examples: * `variable: '--my-font'`: The CSS variable `--my-font` is declared ### [`declarations`](#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` * Optional Examples: * `declarations: [{ prop: 'ascent-override', value: '90%' }]` [Applying Styles](#applying-styles) ----------------------------------- You can apply the font styles in three ways: * [`className`](#classname) * [`style`](#style-1) * [CSS Variables](#css-variables) ### [`className`](#classname) Returns a read-only CSS `className` for the loaded font to be passed to an HTML element. <p className={inter.className}>Hello, Next.js!</p> ### [`style`](#style-1) Returns a read-only CSS `style` object for the loaded font to be passed to an HTML element, including `style.fontFamily` to access the font family name and fallback fonts. <p style={inter.style}>Hello World</p> ### [CSS Variables](#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 the CSS variable is defined and set the variable option of the font loader object as follows: app/page.tsx TypeScript JavaScriptTypeScript import { Inter } from 'next/font/google' import styles from '../styles/component.module.css' const inter = Inter({ variable: '--font-inter', }) To use the font, set the `className` of the parent container of the text you would like to style to the font loader's `variable` value and the `className` of the text to the `styles` property from the external CSS file. app/page.tsx TypeScript JavaScriptTypeScript <main className={inter.variable}> <p className={styles.text}>Hello World</p> </main> Define the `text` selector class in the `component.module.css` CSS file as follows: styles/component.module.css .text { font-family: var(--font-inter); font-weight: 200; font-style: italic; } In the example above, the text `Hello World` is styled using the `Inter` font and the generated font fallback with `font-weight: 200` and `font-style: italic`. [Using a font definitions file](#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 load it in one place and import the related font object where you need it. This is done using a font definitions file. For example, create a `fonts.ts` file in a `styles` folder at the root of your app directory. Then, specify your font definitions as follows: styles/fonts.ts TypeScript JavaScriptTypeScript 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 a non-variable font const sourceCodePro400 = Source_Sans_3({ weight: '400' }) const sourceCodePro700 = Source_Sans_3({ weight: '700' }) // define a custom local font where GreatVibes-Regular.ttf is stored in the styles folder const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' }) export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes } You can now use these definitions in your code as follows: app/page.tsx TypeScript JavaScriptTypeScript import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts' export default function Page() { return ( <div> <p className={inter.className}>Hello world using Inter font</p> <p style={lora.style}>Hello world using Lora font</p> <p className={sourceCodePro700.className}> Hello world using Source_Sans_3 font with weight 700 </p> <p className={greatVibes.className}>My title in Great Vibes font</p> </div> ) } To make it easier to access the font definitions in your code, you can define a path alias in your `tsconfig.json` or `jsconfig.json` files as follows: tsconfig.json { "compilerOptions": { "paths": { "@/fonts": ["./styles/fonts"] } } } You can now import any font definition as follows: app/about/page.tsx TypeScript JavaScriptTypeScript import { greatVibes, sourceCodePro400 } from '@/fonts' [Version Changes](#version-changes) ----------------------------------- Version Changes `v13.2.0` `@next/font` renamed to `next/font`. Installation no longer required. `v13.0.0` `@next/font` was added. [Previous Components ](/docs/app/api-reference/components) [Next <Image> ](/docs/app/api-reference/components/image) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"93883d981a9cc1f02d8c334667d5c882\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/error-handling
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [ Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [How error.js Works](#how-errorjs-works) * [Recovering From Errors](#recovering-from-errors) * [Nested Routes](#nested-routes) * [Handling Errors in Layouts](#handling-errors-in-layouts) * [Handling Errors in Root Layouts](#handling-errors-in-root-layouts) * [Handling Server Errors](#handling-server-errors) * [Securing Sensitive Error Information](#securing-sensitive-error-information) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/05-error-handling.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Error Handling Error Handling ============== The `error.js` file convention allows you to gracefully handle unexpected runtime errors in [nested routes](/docs/app/building-your-application/routing#nested-routes). * Automatically wrap a route segment and its nested children in a [React Error Boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary). * Create error UI tailored to specific segments using the file-system hierarchy to adjust granularity. * Isolate errors to affected segments while keeping the rest of the application functional. * Add functionality to attempt to recover from an error without a full page reload. Create error UI by adding an `error.js` file inside a route segment and exporting a React component: ![error.js special file](/_next/image?url=%2Fdocs%2Flight%2Ferror-special-file.png&w=3840&q=75)![error.js special file](/_next/image?url=%2Fdocs%2Fdark%2Ferror-special-file.png&w=3840&q=75) app/dashboard/error.tsx TypeScript JavaScriptTypeScript 'use client' // Error components must be Client Components import { useEffect } from 'react' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { useEffect(() => { // Log the error to an error reporting service console.error(error) }, [error]) return ( <div> <h2>Something went wrong!</h2> <button onClick={ // Attempt to recover by trying to re-render the segment () => reset() } > Try again </button> </div> ) } ### [How `error.js` Works](#how-errorjs-works) ![How error.js works](/_next/image?url=%2Fdocs%2Flight%2Ferror-overview.png&w=3840&q=75)![How error.js works](/_next/image?url=%2Fdocs%2Fdark%2Ferror-overview.png&w=3840&q=75) * `error.js` automatically creates a [React Error Boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) that **wraps** a nested child segment or `page.js` component. * The React component exported from the `error.js` file is used as the **fallback** component. * If an error is thrown within the error boundary, the error is **contained**, and the fallback component is **rendered**. * When the fallback error component is active, layouts **above** the error boundary **maintain** their state and **remain** interactive, and the error component can display functionality to recover from the error. ### [Recovering From Errors](#recovering-from-errors) The cause of an error can sometimes be temporary. In these cases, simply trying again might resolve the issue. An error component can use the `reset()` function to prompt the user to attempt to recover from the error. When executed, the function will try to re-render the Error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render. app/dashboard/error.tsx TypeScript JavaScriptTypeScript 'use client' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { return ( <div> <h2>Something went wrong!</h2> <button onClick={() => reset()}>Try again</button> </div> ) } ### [Nested Routes](#nested-routes) React components created through [special files](/docs/app/building-your-application/routing#file-conventions) are rendered in a [specific nested hierarchy](/docs/app/building-your-application/routing#component-hierarchy). For example, a nested route with two segments that both include `layout.js` and `error.js` files are rendered in the following _simplified_ component hierarchy: ![Nested Error Component Hierarchy](/_next/image?url=%2Fdocs%2Flight%2Fnested-error-component-hierarchy.png&w=3840&q=75)![Nested Error Component Hierarchy](/_next/image?url=%2Fdocs%2Fdark%2Fnested-error-component-hierarchy.png&w=3840&q=75) The nested component hierarchy has implications for the behavior of `error.js` files across a nested route: * Errors bubble up to the nearest parent error boundary. This means an `error.js` file will handle errors for all its nested child segments. More or less granular error UI can be achieved by placing `error.js` files at different levels in the nested folders of a route. * An `error.js` boundary will **not** handle errors thrown in a `layout.js` component in the **same** segment because the error boundary is nested **inside** that layout's component. ### [Handling Errors in Layouts](#handling-errors-in-layouts) `error.js` boundaries do **not** catch errors thrown in `layout.js` or `template.js` components of the **same segment**. This [intentional hierarchy](#nested-routes) keeps important UI that is shared between sibling routes (such as navigation) visible and functional when an error occurs. To handle errors within a specific layout or template, place an `error.js` file in the layout's parent segment. To handle errors within the root layout or template, use a variation of `error.js` called `global-error.js`. ### [Handling Errors in Root Layouts](#handling-errors-in-root-layouts) The root `app/error.js` boundary does **not** catch errors thrown in the root `app/layout.js` or `app/template.js` component. To specifically handle errors in these root components, use a variation of `error.js` called `app/global-error.js` located in the root `app` directory. Unlike the root `error.js`, the `global-error.js` error boundary wraps the **entire** application, and its fallback component replaces the root layout when active. Because of this, it is important to note that `global-error.js` **must** define its own `<html>` and `<body>` tags. `global-error.js` is the least granular error UI and can be considered "catch-all" error handling for the whole application. It is unlikely to be triggered often as root components are typically less dynamic, and other `error.js` boundaries will catch most errors. Even if a `global-error.js` is defined, it is still recommended to define a root `error.js` whose fallback component will be rendered **within** the root layout, which includes globally shared UI and branding. app/global-error.tsx TypeScript JavaScriptTypeScript 'use client' export default function GlobalError({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { return ( <html> <body> <h2>Something went wrong!</h2> <button onClick={() => reset()}>Try again</button> </body> </html> ) } > **Good to know**: > > * `global-error.js` is only enabled in production. In development, our error overlay will show instead. ### [Handling Server Errors](#handling-server-errors) If an error is thrown inside a Server Component, Next.js will forward an `Error` object (stripped of sensitive error information in production) to the nearest `error.js` file as the `error` prop. #### [Securing Sensitive Error Information](#securing-sensitive-error-information) During production, the `Error` object forwarded to the client only includes a generic `message` and `digest` property. This is a security precaution to avoid leaking potentially sensitive details included in the error to the client. The `message` property contains a generic message about the error and the `digest` property contains an automatically generated hash of the error that can be used to match the corresponding error in server-side logs. During development, the `Error` object forwarded to the client will be serialized and include the `message` of the original error for easier debugging. Next Steps ---------- [ App Router ... File Conventions ### error.js API reference for the error.js special file. ](/docs/app/api-reference/file-conventions/error) [Previous Loading UI and Streaming ](/docs/app/building-your-application/routing/loading-ui-and-streaming) [Next Redirecting ](/docs/app/building-your-application/routing/redirecting) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"c67fec8f03389b8ba88d6ead1e851f7e\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Built-in Components](#built-in-components) * [Metadata](#metadata) * [Static Assets](#static-assets) * [Analytics and Monitoring](#analytics-and-monitoring) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Optimizing Optimizations ============= Next.js comes with a variety of built-in optimizations designed to improve your application's speed and [Core Web Vitals](https://web.dev/vitals/). This guide will cover the optimizations you can leverage to enhance your user experience. [Built-in Components](#built-in-components) ------------------------------------------- Built-in components abstract away the complexity of implementing common UI optimizations. These components are: * **Images**: Built on the native `<img>` element. The Image Component optimizes images for performance by lazy loading and automatically resizing images based on device size. * **Link**: Built on the native `<a>` tags. The Link Component prefetches pages in the background, for faster and smoother page transitions. * **Scripts**: Built on the native `<script>` tags. The Script Component gives you control over loading and execution of third-party scripts. [Metadata](#metadata) --------------------- Metadata helps search engines understand your content better (which can result in better SEO), and allows you to customize how your content is presented on social media, helping you create a more engaging and consistent user experience across various platforms. The Metadata API in Next.js allows you to modify the `<head>` element of a page. You can configure metadata in two ways: * **Config-based Metadata**: Export a [static `metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object) or a dynamic [`generateMetadata` function](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) in a `layout.js` or `page.js` file. * **File-based Metadata**: Add static or dynamically generated special files to route segments. Additionally, you can create dynamic Open Graph Images using JSX and CSS with [imageResponse](/docs/app/api-reference/functions/image-response) constructor. [Static Assets](#static-assets) ------------------------------- Next.js `/public` folder can be used to serve static assets like images, fonts, and other files. Files inside `/public` can also be cached by CDN providers so that they are delivered efficiently. [Analytics and Monitoring](#analytics-and-monitoring) ----------------------------------------------------- For large applications, Next.js integrates with popular analytics and monitoring tools to help you understand how your application is performing. Learn more in the [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) and [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) guides. [ ### Images Optimize your images with the built-in \`next/image\` component. ](/docs/app/building-your-application/optimizing/images)[ ### Videos Recommendations and best practices for optimizing videos in your Next.js application. ](/docs/app/building-your-application/optimizing/videos)[ ### Fonts Optimize your application's web fonts with the built-in \`next/font\` loaders. ](/docs/app/building-your-application/optimizing/fonts)[ ### Metadata Use the Metadata API to define metadata in any layout or page. ](/docs/app/building-your-application/optimizing/metadata)[ ### Scripts Optimize 3rd party scripts with the built-in Script component. ](/docs/app/building-your-application/optimizing/scripts)[ ### Bundle Analyzer Analyze the size of your JavaScript bundles using the @next/bundle-analyzer plugin. ](/docs/app/building-your-application/optimizing/bundle-analyzer)[ ### Lazy Loading Lazy load imported libraries and React Components to improve your application's loading performance. ](/docs/app/building-your-application/optimizing/lazy-loading)[ ### Analytics Measure and track page performance using Next.js Speed Insights ](/docs/app/building-your-application/optimizing/analytics)[ ### Instrumentation Learn how to use instrumentation to run code at server startup in your Next.js app ](/docs/app/building-your-application/optimizing/instrumentation)[ ### OpenTelemetry Learn how to instrument your Next.js app with OpenTelemetry. ](/docs/app/building-your-application/optimizing/open-telemetry)[ ### Static Assets Next.js allows you to serve static files, like images, in the public directory. You can learn how it works here. ](/docs/app/building-your-application/optimizing/static-assets)[ ### Third Party Libraries Optimize the performance of third-party libraries in your application with the \`@next/third-parties\` package. ](/docs/app/building-your-application/optimizing/third-party-libraries)[ ### Memory Usage Optimize memory used by your application in development and production. ](/docs/app/building-your-application/optimizing/memory-usage) [Previous Sass ](/docs/app/building-your-application/styling/sass) [Next Images ](/docs/app/building-your-application/optimizing/images) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"a3d4efb5c76bcf6f5180429a18c46cd8\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/image-response
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Supported CSS Properties](#supported-css-properties) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/image-response.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)ImageResponse ImageResponse ============= The `ImageResponse` constructor allows you to generate dynamic images using JSX and CSS. This is useful for generating social media images such as Open Graph images, Twitter cards, and more. The following options are available for `ImageResponse`: import { ImageResponse } from 'next/og' new ImageResponse( element: ReactElement, options: { width?: number = 1200 height?: number = 630 emoji?: 'twemoji' | 'blobmoji' | 'noto' | 'openmoji' = 'twemoji', fonts?: { name: string, data: ArrayBuffer, weight: number, style: 'normal' | 'italic' }[] debug?: boolean = false // Options that will be passed to the HTTP response status?: number = 200 statusText?: string headers?: Record<string, string> }, ) [Supported CSS Properties](#supported-css-properties) ----------------------------------------------------- Please refer to [Satori’s documentation](https://github.com/vercel/satori#css) for a list of supported HTML and CSS features. [Version History](#version-history) ----------------------------------- Version Changes `v14.0.0` `ImageResponse` moved from `next/server` to `next/og` `v13.3.0` `ImageResponse` can be imported from `next/server`. `v13.0.0` `ImageResponse` introduced via `@vercel/og` package. [Previous headers ](/docs/app/api-reference/functions/headers) [Next NextRequest ](/docs/app/api-reference/functions/next-request) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"dae2e7f13ba1abd3c12d23e1c9311195\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/next-request
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [ NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [cookies](#cookies) * [set(name, value)](#setname-value) * [get(name)](#getname) * [getAll()](#getall) * [delete(name)](#deletename) * [has(name)](#hasname) * [clear()](#clear) * [nextUrl](#nexturl) * [ip](#ip) * [geo](#geo) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/next-request.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)NextRequest NextRequest =========== NextRequest extends the [Web Request API](https://developer.mozilla.org/docs/Web/API/Request) with additional convenience methods. [`cookies`](#cookies) --------------------- Read or mutate the [`Set-Cookie`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie) header of the request. ### [`set(name, value)`](#setname-value) Given a name, set a cookie with the given value on the request. // Given incoming request /home // Set a cookie to hide the banner // request will have a `Set-Cookie:show-banner=false;path=/home` header request.cookies.set('show-banner', 'false') ### [`get(name)`](#getname) Given a cookie name, return the value of the cookie. If the cookie is not found, `undefined` is returned. If multiple cookies are found, the first one is returned. // Given incoming request /home // { name: 'show-banner', value: 'false', Path: '/home' } request.cookies.get('show-banner') ### [`getAll()`](#getall) Given a cookie name, return the values of the cookie. If no name is given, return all cookies on the request. // Given incoming request /home // [ // { name: 'experiments', value: 'new-pricing-page', Path: '/home' }, // { name: 'experiments', value: 'winter-launch', Path: '/home' }, // ] request.cookies.getAll('experiments') // Alternatively, get all cookies for the request request.cookies.getAll() ### [`delete(name)`](#deletename) Given a cookie name, delete the cookie from the request. // Returns true for deleted, false is nothing is deleted request.cookies.delete('experiments') ### [`has(name)`](#hasname) Given a cookie name, return `true` if the cookie exists on the request. // Returns true if cookie exists, false if it does not request.cookies.has('experiments') ### [`clear()`](#clear) Remove the `Set-Cookie` header from the request. request.cookies.clear() [`nextUrl`](#nexturl) --------------------- Extends the native [`URL`](https://developer.mozilla.org/docs/Web/API/URL) API with additional convenience methods, including Next.js specific properties. // Given a request to /home, pathname is /home request.nextUrl.pathname // Given a request to /home?name=lee, searchParams is { 'name': 'lee' } request.nextUrl.searchParams The following options are available: Property Type Description `basePath` `string` The [base path](/docs/app/api-reference/next-config-js/basePath) of the URL. `buildId` `string` | `undefined` The build identifier of the Next.js application. Can be [customized](/docs/app/api-reference/next-config-js/generateBuildId). `pathname` `string` The pathname of the URL. `searchParams` `Object` The search parameters of the URL. > **Note:** The internationalization properties from the Pages Router are not available for usage in the App Router. Learn more about [internationalization with the App Router](/docs/app/building-your-application/routing/internationalization). [`ip`](#ip) ----------- The `ip` property is a string that contains the IP address of the request. This value can optionally be provided by your hosting platform. > **Good to know:** On [Vercel](https://vercel.com/docs/frameworks/nextjs?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), this value is provided by default. On other platforms, you can use the [`X-Forwarded-For`](https://developer.mozilla.org/docs/Web/HTTP/Headers/X-Forwarded-For) header to provide the IP address. // Provided by Vercel request.ip // Self-hosting request.headers.get('X-Forwarded-For') [`geo`](#geo) ------------- The `geo` property is an object that contains the geographic information of the request. This value can optionally be provided by your hosting platform. > **Good to know:** On [Vercel](https://vercel.com/docs/frameworks/nextjs?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), this value is provided by default. On other platforms, you can use the [`X-Forwarded-For`](https://developer.mozilla.org/docs/Web/HTTP/Headers/X-Forwarded-For) header to provide the IP address, then use a [third-party service](https://ip-api.com/) to lookup the geographic information. // Provided by Vercel request.geo.city request.geo.country request.geo.region request.geo.latitude request.geo.longitude // Self-hosting function getGeo(request) { let ip = request.headers.get('X-Forwarded-For') // Use a third-party service to lookup the geographic information } [Previous ImageResponse ](/docs/app/api-reference/functions/image-response) [Next NextResponse ](/docs/app/api-reference/functions/next-response) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"0702f82ef8f7c6fd18f1afa6bfab310e\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/components/image
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [ <Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Props](#props) * [Required Props](#required-props) * [src](#src) * [width](#width) * [height](#height) * [alt](#alt) * [Optional Props](#optional-props) * [loader](#loader) * [fill](#fill) * [sizes](#sizes) * [quality](#quality) * [priority](#priority) * [placeholder](#placeholder) * [Advanced Props](#advanced-props) * [style](#style) * [onLoadingComplete](#onloadingcomplete) * [onLoad](#onload) * [onError](#onerror) * [loading](#loading) * [blurDataURL](#blurdataurl) * [unoptimized](#unoptimized) * [overrideSrc](#overridesrc) * [Other Props](#other-props) * [Configuration Options](#configuration-options) * [remotePatterns](#remotepatterns) * [domains](#domains) * [loaderFile](#loaderfile) * [Advanced](#advanced) * [deviceSizes](#devicesizes) * [imageSizes](#imagesizes) * [formats](#formats) * [Caching Behavior](#caching-behavior) * [minimumCacheTTL](#minimumcachettl) * [disableStaticImages](#disablestaticimages) * [dangerouslyAllowSVG](#dangerouslyallowsvg) * [Animated Images](#animated-images) * [Responsive Images](#responsive-images) * [Responsive image using a static import](#responsive-image-using-a-static-import) * [Responsive image with aspect ratio](#responsive-image-with-aspect-ratio) * [Responsive image with fill](#responsive-image-with-fill) * [Theme Detection CSS](#theme-detection-css) * [getImageProps](#getimageprops) * [Theme Detection Picture](#theme-detection-picture) * [Art Direction](#art-direction) * [Background CSS](#background-css) * [Known Browser Bugs](#known-browser-bugs) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/01-components/image.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Components](/docs/app/api-reference/components)<Image> <Image> ======= Examples * [Image Component](https://github.com/vercel/next.js/tree/canary/examples/image-component) This API reference will help you understand how to use [props](#props) and [configuration options](#configuration-options) available for the Image Component. For features and usage, please see the [Image Component](/docs/app/building-your-application/optimizing/images) page. app/page.js import Image from 'next/image' export default function Page() { return ( <Image src="/profile.png" width={500} height={500} alt="Picture of the author" /> ) } [Props](#props) --------------- Here's a summary of the props available for the Image Component: Prop Example Type Status [`src`](#src) `src="/profile.png"` String Required [`width`](#width) `width={500}` Integer (px) Required [`height`](#height) `height={500}` Integer (px) Required [`alt`](#alt) `alt="Picture of the author"` String Required [`loader`](#loader) `loader={imageLoader}` Function \- [`fill`](#fill) `fill={true}` Boolean \- [`sizes`](#sizes) `sizes="(max-width: 768px) 100vw, 33vw"` String \- [`quality`](#quality) `quality={80}` Integer (1-100) \- [`priority`](#priority) `priority={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 \- [`overrideSrc`](#overridesrc) `overrideSrc="/seo.png"` String \- [Required Props](#required-props) --------------------------------- The Image Component requires the following properties: `src`, `width`, `height`, and `alt`. app/page.js import Image from 'next/image' export default function Page() { return ( <div> <Image src="/profile.png" width={500} height={500} alt="Picture of the author" /> </div> ) } ### [`src`](#src) Must be one of the following: * A [statically imported](/docs/app/building-your-application/optimizing/images#local-images) image file * A path string. This can be either an absolute external URL, or an internal path depending on the [loader](#loader) prop. When using an external URL, you must add it to [remotePatterns](#remotepatterns) in `next.config.js`. ### [`width`](#width) The `width` property represents the _rendered_ width in pixels, so it will affect how large the image appears. Required, except for [statically imported images](/docs/app/building-your-application/optimizing/images#local-images) or images with the [`fill` property](#fill). ### [`height`](#height) The `height` property represents the _rendered_ height in pixels, so it will affect how large the image appears. Required, except for [statically imported images](/docs/app/building-your-application/optimizing/images#local-images) or images with the [`fill` property](#fill). ### [`alt`](#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](https://html.spec.whatwg.org/multipage/images.html#alt) [Optional Props](#optional-props) --------------------------------- The `<Image />` component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the [Advanced Props](#advanced-props) section. ### [`loader`](#loader) A custom function used to resolve image URLs. A `loader` is a function returning a URL string for the image, given the following parameters: * [`src`](#src) * [`width`](#width) * [`quality`](#quality) Here is an example of using a custom loader: '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} /> ) } > **Good to know**: Using props like `loader`, which accept a function, requires using [Client Components](/docs/app/building-your-application/rendering/client-components) 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. ### [`fill`](#fill) fill={true} // {true} | {false} A boolean that causes the image to fill the parent element, which is useful when the [`width`](#width) and [`height`](#height) are unknown. The parent element _must_ assign `position: "relative"`, `position: "fixed"`, or `position: "absolute"` style. By default, the img element will automatically be assigned the `position: "absolute"` style. If no styles are applied to the image, the image will stretch to fit the container. You may prefer to set `object-fit: "contain"` for an image which is letterboxed to fit the container and preserve aspect ratio. Alternatively, `object-fit: "cover"` will cause the image to fill the entire container and be cropped to preserve aspect ratio. For this to look correct, the `overflow: "hidden"` style should be assigned to the parent element. For more information, see also: * [`position`](https://developer.mozilla.org/docs/Web/CSS/position) * [`object-fit`](https://developer.mozilla.org/docs/Web/CSS/object-fit) * [`object-position`](https://developer.mozilla.org/docs/Web/CSS/object-position) ### [`sizes`](#sizes) A string, similar to a media query, that provides information about how wide the image will be at different breakpoints. The value of `sizes` will greatly affect performance for images using [`fill`](#fill) or which are [styled to have a responsive size](#responsive-images). The `sizes` property serves two important purposes related to image performance: * First, the value of `sizes` is used by the browser to determine which size of the image to download, from `next/image`'s automatically generated `srcset`. When the browser chooses, it does not yet know the size of the image on the page, so it selects an image that is the same size or larger than the viewport. The `sizes` property allows you to tell the browser that the image will actually be smaller than full screen. If you don't specify a `sizes` value in an image with the `fill` property, a default value of `100vw` (full screen width) is used. * Second, the `sizes` property changes the behavior of the automatically generated `srcset` value. If no `sizes` value is present, a small `srcset` is generated, suitable for a fixed-size image (1x/2x/etc). If `sizes` is defined, a large `srcset` is generated, suitable for a responsive image (640w/750w/etc). If the `sizes` property includes sizes such as `50vw`, which represent a percentage of the viewport width, then the `srcset` is trimmed to not include any values which are too small to ever be necessary. For example, if you know your styling will cause an image to be full-width on mobile devices, in a 2-column layout on tablets, and a 3-column layout on desktop displays, you should include a sizes property such as the following: 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> ) } This example `sizes` could have a dramatic effect on performance metrics. Without the `33vw` sizes, the image selected from the server would be 3 times as wide as it needs to be. Because file size is proportional to the square of the width, without `sizes` the user would download an image that's 9 times larger than necessary. Learn more about `srcset` and `sizes`: * [web.dev](https://web.dev/learn/design/responsive-images/#sizes) * [mdn](https://developer.mozilla.org/docs/Web/HTML/Element/img#sizes) ### [`quality`](#quality) quality={75} // {number 1-100} The quality of the optimized image, an integer between `1` and `100`, where `100` is the best quality and therefore largest file size. Defaults to `75`. ### [`priority`](#priority) priority={false} // {false} | {true} When true, the image will be considered high priority and [preload](https://web.dev/preload-responsive-images/). Lazy loading is automatically disabled for images using `priority`. You should use the `priority` property on any image detected as the [Largest Contentful Paint (LCP)](https://nextjs.org/learn/seo/web-performance/lcp) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes. Should only be used when the image is visible above the fold. Defaults to `false`. ### [`placeholder`](#placeholder) placeholder = 'empty' // "empty" | "blur" | "data:image/..." A placeholder to use while the image is loading. Possible values are `blur`, `empty`, or `data:image/...`. Defaults to `empty`. When `blur`, the [`blurDataURL`](#blurdataurl) property will be used as the placeholder. If `src` is an object from a [static import](/docs/app/building-your-application/optimizing/images#local-images) and the imported image is `.jpg`, `.png`, `.webp`, or `.avif`, then `blurDataURL` will be automatically populated, except when the image is detected to be animated. For dynamic images, you must provide the [`blurDataURL`](#blurdataurl) property. Solutions such as [Plaiceholder](https://github.com/joe-bell/plaiceholder) can help with `base64` generation. When `data:image/...`, the [Data URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) will be used as the placeholder while the image is loading. When `empty`, there will be no placeholder while the image is loading, only empty space. Try it out: * [Demo the `blur` placeholder](https://image-component.nextjs.gallery/placeholder) * [Demo the shimmer effect with data URL `placeholder` prop](https://image-component.nextjs.gallery/shimmer) * [Demo the color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color) [Advanced Props](#advanced-props) --------------------------------- In some cases, you may need more advanced usage. The `<Image />` component optionally accepts the following advanced properties. ### [`style`](#style) Allows passing CSS styles to the underlying image element. components/ProfileImage.js const imageStyle = { borderRadius: '50%', border: '1px solid #fff', } export default function ProfileImage() { return <Image src="..." style={imageStyle} /> } Remember that the required width and height props can interact with your styling. If you use styling to modify an image's width, you should also style its height to `auto` to preserve its intrinsic aspect ratio, or your image will be distorted. ### [`onLoadingComplete`](#onloadingcomplete) 'use client' <Image onLoadingComplete={(img) => console.log(img.naturalWidth)} /> > **Warning**: Deprecated since Next.js 14 in favor of [`onLoad`](#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, a reference to the underlying `<img>` element. > **Good to know**: Using props like `onLoadingComplete`, which accept a function, requires using [Client Components](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. ### [`onLoad`](#onload) <Image onLoad={(e) => console.log(e.target.naturalWidth)} /> 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](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. ### [`onError`](#onerror) <Image onError={(e) => console.error(e.target.id)} /> 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](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. ### [`loading`](#loading) > **Recommendation**: This property is only meant for advanced use cases. Switching an image to load with `eager` will normally **hurt performance**. We recommend using the [`priority`](#priority) property instead, which will eagerly preload the image. loading = 'lazy' // {lazy} | {eager} The loading behavior of the image. Defaults to `lazy`. When `lazy`, defer loading the image until it reaches a calculated distance from the viewport. When `eager`, load the image immediately. Learn more about the [`loading` attribute](https://developer.mozilla.org/docs/Web/HTML/Element/img#loading). ### [`blurDataURL`](#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 `src` image successfully loads. Only takes effect when combined with [`placeholder="blur"`](#placeholder). Must be a base64-encoded image. It will be enlarged and blurred, so a very small image (10px or less) is recommended. Including larger images as placeholders may harm your application performance. Try it out: * [Demo the default `blurDataURL` prop](https://image-component.nextjs.gallery/placeholder) * [Demo the color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color) You can also [generate a solid color Data URL](https://png-pixel.com) to match the image. ### [`unoptimized`](#unoptimized) unoptimized = {false} // {false} | {true} When true, the source image will be served as-is instead of changing quality, size, or format. Defaults to `false`. import Image from 'next/image' const UnoptimizedImage = (props) => { return <Image {...props} unoptimized /> } 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 module.exports = { images: { unoptimized: true, }, } ### [`overrideSrc`](#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 <Image src="/me.jpg" /> output.html <img srcset=" /_next/image?url=%2Fme.jpg&w=640&q=75 1x, /_next/image?url=%2Fme.jpg&w=828&q=75 2x " src="/_next/image?url=%2Fme.jpg&w=828&q=75" /> 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 <Image src="/me.jpg" overrideSrc="/override.jpg" /> output.html <img srcset=" /_next/image?url=%2Fme.jpg&w=640&q=75 1x, /_next/image?url=%2Fme.jpg&w=828&q=75 2x " src="/override.jpg" /> ### [Other Props](#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. * `decoding`. It is always `"async"`. [Configuration Options](#configuration-options) ----------------------------------------------- In addition to props, you can configure the Image Component in `next.config.js`. The following options are available: ### [`remotePatterns`](#remotepatterns) To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below: next.config.js module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 'example.com', port: '', pathname: '/account123/**', }, ], }, } > **Good to know**: The example above will ensure the `src` property of `next/image` must start with `https://example.com/account123/`. Any other protocol, hostname, port, or unmatched path will respond with 400 Bad Request. Below is another example of the `remotePatterns` property in the `next.config.js` file: next.config.js module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: '**.example.com', port: '', }, ], }, } > **Good to know**: The example above will ensure the `src` property of `next/image` must start with `https://img1.example.com` or `https://me.avatar.example.com` or any number of subdomains. Any other protocol, port, or unmatched hostname will respond with 400 Bad Request. 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 The `**` syntax does not work in the middle of the pattern. > **Good to know**: When omitting `protocol`, `port` or `pathname`, then the wildcard `**` is implied. This is not recommended because it may allow malicious actors to optimize urls you did not intend. ### [`domains`](#domains) > **Warning**: Deprecated since Next.js 14 in favor of strict [`remotePatterns`](#remotepatterns) in order to protect your application from malicious users. Only use `domains` if you own all the content served from the domain. 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. Below is an example of the `domains` property in the `next.config.js` file: next.config.js module.exports = { images: { domains: ['assets.acme.com'], }, } ### [`loaderFile`](#loaderfile) If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the `loaderFile` in your `next.config.js` like the following: next.config.js module.exports = { images: { loader: 'custom', loaderFile: './my/image/loader.js', }, } This must point to a file relative to the root of your Next.js application. The file must export a default function that returns a string, for example: my/image/loader.js 'use client' export default function myImageLoader({ src, width, quality }) { return `https://example.com/${src}?w=${width}&q=${quality || 75}` } Alternatively, you can use the [`loader` prop](#loader) to configure each instance of `next/image`. Examples: * [Custom Image Loader Configuration](/docs/app/api-reference/next-config-js/images#example-loader-configuration) > **Good to know**: Customizing the image loader file, which accepts a function, requires using [Client Components](/docs/app/building-your-application/rendering/client-components) to serialize the provided function. [Advanced](#advanced) --------------------- The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates. ### [`deviceSizes`](#devicesizes) If you know the expected device widths of your users, you can specify a list of device width breakpoints using the `deviceSizes` property in `next.config.js`. These widths are used when the `next/image` component uses [`sizes`](#sizes) prop to ensure the correct image is served for user's device. If no configuration is provided, the default below is used. next.config.js module.exports = { images: { deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], }, } ### [`imageSizes`](#imagesizes) You can specify a list of image widths using the `images.imageSizes` property in your `next.config.js` file. 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)s. The reason there are two separate lists is that 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.** If no configuration is provided, the default below is used. next.config.js module.exports = { images: { imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], }, } ### [`formats`](#formats) The default [Image Optimization API](#loader) will automatically detect the browser's supported image formats via the request's `Accept` header. If the `Accept` head 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](#animated-images)), the Image Optimization API will fallback to the original image's format. If no configuration is provided, the default below is used. next.config.js module.exports = { images: { formats: ['image/webp'], }, } You can enable AVIF support with the following configuration. next.config.js module.exports = { images: { formats: ['image/avif', 'image/webp'], }, } > **Good to know**: > > * AVIF generally takes 20% 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 and then subsequent requests that are cached will be faster. > * If you self-host with a Proxy/CDN in front of Next.js, you must configure the Proxy to forward the `Accept` header. [Caching Behavior](#caching-behavior) ------------------------------------- The following describes the caching algorithm for the default [loader](#loader). For all other loaders, please refer to your cloud provider's documentation. Images are optimized dynamically upon request and stored in the `<distDir>/cache/images` directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the expired image is served stale immediately. Then the image is optimized again in the background (also called revalidation) and saved to the cache with the new expiration date. The cache status of an image can be determined by reading the value of the `x-nextjs-cache` response header. The possible values are the following: * `MISS` - the path is not in the cache (occurs at most once, on the first visit) * `STALE` - the path is in the cache but exceeded the revalidate time so it will be updated in the background * `HIT` - the path is in the cache and has not exceeded the revalidate time The expiration (or rather Max Age) is defined by either the [`minimumCacheTTL`](#minimumcachettl) configuration or the upstream image `Cache-Control` header, whichever is larger. Specifically, the `max-age` value of the `Cache-Control` header is used. If both `s-maxage` and `max-age` are found, then `s-maxage` is preferred. The `max-age` is also passed-through to any downstream clients including CDNs and browsers. * You can configure [`minimumCacheTTL`](#minimumcachettl) to increase the cache duration when the upstream image does not include `Cache-Control` header or the value is very low. * You can configure [`deviceSizes`](#devicesizes) and [`imageSizes`](#imagesizes) to reduce the total number of possible generated images. * You can configure [formats](#formats) to disable multiple formats in favor of a single image format. ### [`minimumCacheTTL`](#minimumcachettl) You can 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/building-your-application/optimizing/images#local-images) which will automatically hash the file contents and cache the image forever with a `Cache-Control` header of `immutable`. next.config.js module.exports = { images: { minimumCacheTTL: 60, }, } 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/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 `<distDir>/cache/images`. ### [`disableStaticImages`](#disablestaticimages) 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 module.exports = { images: { disableStaticImages: true, }, } ### [`dangerouslyAllowSVG`](#dangerouslyallowsvg) The default [loader](#loader) does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, 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/next-config-js/headers#content-security-policy). Therefore, we recommended using the [`unoptimized`](#unoptimized) prop when the [`src`](#src) prop is known to be SVG. This happens automatically when `src` ends with `".svg"`. However, if you need to serve SVG images with the default Image Optimization API, you can set `dangerouslyAllowSVG` inside your `next.config.js`: next.config.js module.exports = { images: { dangerouslyAllowSVG: true, contentDispositionType: 'attachment', contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", }, } 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. [Animated Images](#animated-images) ----------------------------------- The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is. Auto-detection for animated files is best-effort and supports GIF, APNG, and WebP. If you want to explicitly bypass Image Optimization for a given animated image, use the [unoptimized](#unoptimized) prop. [Responsive Images](#responsive-images) --------------------------------------- The default generated `srcset` contains `1x` and `2x` images in order to support different device pixel ratios. However, you may wish to render a responsive image that stretches with the viewport. In that case, you'll need to set [`sizes`](#sizes) as well as `style` (or `className`). You can render a responsive image using one of the following methods below. ### [Responsive image using a static import](#responsive-image-using-a-static-import) If the source image is not dynamic, you can statically import to create a responsive image: components/author.js import Image from 'next/image' import me from '../photos/me.jpg' export default function Author() { return ( <Image src={me} alt="Picture of the author" sizes="100vw" style={{ width: '100%', height: 'auto', }} /> ) } Try it out: * [Demo the image responsive to viewport](https://image-component.nextjs.gallery/responsive) ### [Responsive image with aspect ratio](#responsive-image-with-aspect-ratio) If the source image is a dynamic or a remote url, you will also need to provide `width` and `height` to set the correct aspect ratio of the responsive image: components/page.js 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} /> ) } Try it out: * [Demo the image responsive to viewport](https://image-component.nextjs.gallery/responsive) ### [Responsive image with `fill`](#responsive-image-with-fill) If you don't know the aspect ratio, you will need to set the [`fill`](#fill) prop and set `position: relative` on the parent. Optionally, you can set `object-fit` style depending on the desired stretch vs crop behavior: app/page.js import Image from 'next/image' export default function Page({ photoUrl }) { return ( <div style={{ position: 'relative', width: '300px', height: '500px' }}> <Image src={photoUrl} alt="Picture of the author" sizes="300px" fill style={{ objectFit: 'contain', }} /> </div> ) } Try it out: * [Demo the `fill` prop](https://image-component.nextjs.gallery/fill) [Theme Detection CSS](#theme-detection-css) ------------------------------------------- If you want to display a different image for light and dark mode, you can create a new component that wraps two `<Image>` components and reveals the correct one based on a CSS media query. components/theme-image.module.css .imgDark { display: none; } @media (prefers-color-scheme: dark) { .imgLight { display: none; } .imgDark { display: unset; } } components/theme-image.tsx TypeScript JavaScriptTypeScript import styles from './theme-image.module.css' import Image, { ImageProps } from 'next/image' type Props = Omit<ImageProps, 'src' | 'priority' | '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} /> </> ) } > **Good to know**: The default behavior of `loading="lazy"` ensures that only the correct image is loaded. You cannot use `priority` or `loading="eager"` because that would cause both images to load. Instead, you can use [`fetchPriority="high"`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/fetchPriority). Try it out: * [Demo light/dark mode theme detection](https://image-component.nextjs.gallery/theme) [getImageProps](#getimageprops) ------------------------------- For more advanced use cases, you can call `getImageProps()` to get the props that would be passed to the underlying `<img>` element, and instead pass to 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. ### [Theme Detection Picture](#theme-detection-picture) If you want to display a different image for light and dark mode, you can use the [`<picture>`](https://developer.mozilla.org/docs/Web/HTML/Element/picture) element to display a different image based on the user's [preferred color scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme). app/page.js import { getImageProps } from 'next/image' export default function Page() { const common = { alt: 'Theme Example', width: 800, height: 400 } const { props: { srcSet: dark }, } = getImageProps({ ...common, src: '/dark.png' }) const { props: { srcSet: light, ...rest }, } = getImageProps({ ...common, src: '/light.png' }) return ( <picture> <source media="(prefers-color-scheme: dark)" srcSet={dark} /> <source media="(prefers-color-scheme: light)" srcSet={light} /> <img {...rest} /> </picture> ) } ### [Art Direction](#art-direction) If you want to display a different image for mobile and desktop, sometimes called [Art Direction](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction), you can provide different `src`, `width`, `height`, and `quality` props to `getImageProps()`. app/page.js 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> ) } ### [Background CSS](#background-css) You can even convert the `srcSet` string to the [`image-set()`](https://developer.mozilla.org/en-US/docs/Web/CSS/image/image-set) CSS function to optimize a background image. app/page.js 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 ( <main style={style}> <h1>Hello World</h1> </main> ) } [Known Browser Bugs](#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 [`priority`](#priority) 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) [Version History](#version-history) ----------------------------------- Version Changes `v14.2.0` `overrideSrc` prop added. `v14.1.0` `getImageProps()` is stable. `v14.0.0` `onLoadingComplete` prop and `domains` config deprecated. `v13.4.14` `placeholder` prop support for `data:/image...` `v13.2.0` `contentDispositionType` configuration added. `v13.0.6` `ref` prop added. `v13.0.0` The `next/image` import was renamed to `next/legacy/image`. The `next/future/image` import was renamed to `next/image`. A [codemod is available](/docs/app/building-your-application/upgrading/codemods#next-image-to-legacy-image) to safely and automatically rename your imports. `<span>` wrapper removed. `layout`, `objectFit`, `objectPosition`, `lazyBoundary`, `lazyRoot` props removed. `alt` is required. `onLoadingComplete` receives reference to `img` element. Built-in loader config removed. `v12.3.0` `remotePatterns` and `unoptimized` configuration is stable. `v12.2.0` Experimental `remotePatterns` and experimental `unoptimized` configuration added. `layout="raw"` removed. `v12.1.1` `style` prop added. Experimental support for `layout="raw"` added. `v12.1.0` `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. `v12.0.9` `lazyRoot` prop added. `v12.0.0` `formats` configuration added. AVIF support added. Wrapper `<div>` changed to `<span>`. `v11.1.0` `onLoadingComplete` and `lazyBoundary` props added. `v11.0.0` `src` prop support for static import. `placeholder` prop added. `blurDataURL` prop added. `v10.0.5` `loader` prop added. `v10.0.1` `layout` prop added. `v10.0.0` `next/image` introduced. [Previous Font ](/docs/app/api-reference/components/font) [Next <Link> ](/docs/app/api-reference/components/link) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"f4c8d41e7bddf7e70a2185f4ffbd965d\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/redirecting
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [ Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [redirect function](#redirect-function) * [permanentRedirect function](#permanentredirect-function) * [useRouter() hook](#userouter-hook) * [redirects in next.config.js](#redirects-in-nextconfigjs) * [NextResponse.redirect in Middleware](#nextresponseredirect-in-middleware) * [Managing redirects at scale (advanced)](#managing-redirects-at-scale-advanced) * [1\. Creating and storing a redirect map](#1-creating-and-storing-a-redirect-map) * [2\. Optimizing data lookup performance](#2-optimizing-data-lookup-performance) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/06-redirecting.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Redirecting Redirecting =========== There are a few ways you can handle redirects in Next.js. This page will go through each available option, use cases, and how to manage large numbers of redirects. API Purpose Where Status Code [`redirect`](#redirect-function) Redirect user after a mutation or event Server Components, Server Actions, Route Handlers 307 (Temporary) or 303 (Server Action) [`permanentRedirect`](#permanentredirect-function) Redirect user after a mutation or event Server Components, Server Actions, Route Handlers 308 (Permanent) [`useRouter`](#userouter-hook) Perform a client-side navigation Event Handlers in Client Components N/A [`redirects` in `next.config.js`](#redirects-in-nextconfigjs) Redirect an incoming request based on a path `next.config.js` file 307 (Temporary) or 308 (Permanent) [`NextResponse.redirect`](#nextresponseredirect-in-middleware) Redirect an incoming request based on a condition Middleware Any [`redirect` function](#redirect-function) ----------------------------------------- The `redirect` function allows you to redirect the user to another URL. You can call `redirect` in [Server Components](/docs/app/building-your-application/rendering/server-components), [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). `redirect` is often used after a mutation or event. For example, creating a post: app/actions.tsx TypeScript JavaScriptTypeScript 'use server' import { redirect } from 'next/navigation' import { revalidatePath } from 'next/cache' export async function createPost(id: string) { try { // Call database } catch (error) { // Handle errors } revalidatePath('/posts') // Update cached posts redirect(`/post/${id}`) // Navigate to the new post page } > **Good to know**: > > * `redirect` returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request. > * `redirect` internally throws an error so it should be called outside of `try/catch` blocks. > * `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](#userouter-hook) instead. > * `redirect` also accepts absolute URLs and can be used to redirect to external links. > * If you'd like to redirect before the render process, use [`next.config.js`](#redirects-in-nextconfigjs) or [Middleware](#nextresponseredirect-in-middleware). See the [`redirect` API reference](/docs/app/api-reference/functions/redirect) for more information. [`permanentRedirect` function](#permanentredirect-function) ----------------------------------------------------------- The `permanentRedirect` function allows you to **permanently** redirect the user to another URL. You can call `permanentRedirect` in [Server Components](/docs/app/building-your-application/rendering/server-components), [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). `permanentRedirect` is often used after a mutation or event that changes an entity's canonical URL, such as updating a user's profile URL after they change their username: app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { permanentRedirect } from 'next/navigation' import { revalidateTag } from 'next/cache' export async function updateUsername(username: string, formData: FormData) { try { // Call database } catch (error) { // Handle errors } revalidateTag('username') // Update all references to the username permanentRedirect(`/profile/${username}`) // Navigate to the new user profile } > **Good to know**: > > * `permanentRedirect` returns a 308 (permanent redirect) status code by default. > * `permanentRedirect` also accepts absolute URLs and can be used to redirect to external links. > * If you'd like to redirect before the render process, use [`next.config.js`](#redirects-in-nextconfigjs) or [Middleware](#nextresponseredirect-in-middleware). See the [`permanentRedirect` API reference](/docs/app/api-reference/functions/permanentRedirect) for more information. [`useRouter()` hook](#userouter-hook) ------------------------------------- If you need to redirect inside an event handler in a Client Component, you can use the `push` method from the `useRouter` hook. For example: app/page.tsx TypeScript JavaScriptTypeScript 'use client' import { useRouter } from 'next/navigation' export default function Page() { const router = useRouter() return ( <button type="button" onClick={() => router.push('/dashboard')}> Dashboard </button> ) } > **Good to know**: > > * If you don't need to programmatically navigate a user, you should use a [`<Link>`](/docs/app/api-reference/components/link) component. See the [`useRouter` API reference](/docs/app/api-reference/functions/use-router) for more information. [`redirects` in `next.config.js`](#redirects-in-nextconfigjs) ------------------------------------------------------------- The `redirects` option in the `next.config.js` file allows you to redirect an incoming request path to a different destination path. This is useful when you change the URL structure of pages or have a list of redirects that are known ahead of time. `redirects` supports [path](/docs/app/api-reference/next-config-js/redirects#path-matching), [header, cookie, and query matching](/docs/app/api-reference/next-config-js/redirects#header-cookie-and-query-matching), giving you the flexibility to redirect users based on an incoming request. To use `redirects`, add the option to your `next.config.js` file: next.config.js module.exports = { async redirects() { return [ // Basic redirect { source: '/about', destination: '/', permanent: true, }, // Wildcard path matching { source: '/blog/:slug', destination: '/news/:slug', permanent: true, }, ] }, } See the [`redirects` API reference](/docs/app/api-reference/next-config-js/redirects) for more information. > **Good to know**: > > * `redirects` can return a 307 (Temporary Redirect) or 308 (Permanent Redirect) status code with the `permanent` option. > * `redirects` may have a limit on platforms. For example, on Vercel, there's a limit of 1,024 redirects. To manage a large number of redirects (1000+), consider creating a custom solution using [Middleware](/docs/app/building-your-application/routing/middleware). See [managing redirects at scale](#managing-redirects-at-scale-advanced) for more. > * `redirects` runs **before** Middleware. [`NextResponse.redirect` in Middleware](#nextresponseredirect-in-middleware) ---------------------------------------------------------------------------- Middleware allows you to run code before a request is completed. Then, based on the incoming request, redirect to a different URL using `NextResponse.redirect`. This is useful if you want to redirect users based on a condition (e.g. authentication, session management, etc) or have [a large number of redirects](#managing-redirects-at-scale-advanced). For example, to redirect the user to a `/login` page if they are not authenticated: middleware.ts TypeScript JavaScriptTypeScript import { NextResponse, NextRequest } from 'next/server' import { authenticate } from 'auth-provider' export function middleware(request: NextRequest) { const isAuthenticated = authenticate(request) // If the user is authenticated, continue as normal if (isAuthenticated) { return NextResponse.next() } // Redirect to login page if not authenticated return NextResponse.redirect(new URL('/login', request.url)) } export const config = { matcher: '/dashboard/:path*', } > **Good to know**: > > * Middleware runs **after** `redirects` in `next.config.js` and **before** rendering. See the [Middleware](/docs/app/building-your-application/routing/middleware) documentation for more information. [Managing redirects at scale (advanced)](#managing-redirects-at-scale-advanced) ------------------------------------------------------------------------------- To manage a large number of redirects (1000+), you may consider creating a custom solution using Middleware. This allows you to handle redirects programmatically without having to redeploy your application. To do this, you'll need to consider: 1. Creating and storing a redirect map. 2. Optimizing data lookup performance. > **Next.js Example**: See our [Middleware with Bloom filter](https://redirects-bloom-filter.vercel.app/) example for an implementation of the recommendations below. ### [1\. Creating and storing a redirect map](#1-creating-and-storing-a-redirect-map) A redirect map is a list of redirects that you can store in a database (usually a key-value store) or JSON file. Consider the following data structure: { "/old": { "destination": "/new", "permanent": true }, "/blog/post-old": { "destination": "/blog/post-new", "permanent": true } } In [Middleware](/docs/app/building-your-application/routing/middleware), you can read from a database such as Vercel's [Edge Config](https://vercel.com/docs/storage/edge-config/get-started?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) or [Redis](https://vercel.com/docs/storage/vercel-kv?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), and redirect the user based on the incoming request: middleware.ts TypeScript JavaScriptTypeScript import { NextResponse, NextRequest } from 'next/server' import { get } from '@vercel/edge-config' type RedirectEntry = { destination: string permanent: boolean } export async function middleware(request: NextRequest) { const pathname = request.nextUrl.pathname const redirectData = await get(pathname) if (redirectData && typeof redirectData === 'string') { const redirectEntry: RedirectEntry = JSON.parse(redirectData) const statusCode = redirectEntry.permanent ? 308 : 307 return NextResponse.redirect(redirectEntry.destination, statusCode) } // No redirect found, continue without redirecting return NextResponse.next() } ### [2\. Optimizing data lookup performance](#2-optimizing-data-lookup-performance) Reading a large dataset for every incoming request can be slow and expensive. There are two ways you can optimize data lookup performance: * Use a database that is optimized for fast reads, such as [Vercel Edge Config](https://vercel.com/docs/storage/edge-config/get-started?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) or [Redis](https://vercel.com/docs/storage/vercel-kv?utm_source=next-site&utm_medium=docs&utm_campaign=next-website). * Use a data lookup strategy such as a [Bloom filter](https://en.wikipedia.org/wiki/Bloom_filter) to efficiently check if a redirect exists **before** reading the larger redirects file or database. Considering the previous example, you can import a generated bloom filter file into Middleware, then, check if the incoming request pathname exists in the bloom filter. If it does, forward the request to a [Route Handler](/docs/app/building-your-application/routing/route-handlers) which will check the actual file and redirect the user to the appropriate URL. This avoids importing a large redirects file into Middleware, which can slow down every incoming request. middleware.ts TypeScript JavaScriptTypeScript import { NextResponse, NextRequest } from 'next/server' import { ScalableBloomFilter } from 'bloom-filters' import GeneratedBloomFilter from './redirects/bloom-filter.json' type RedirectEntry = { destination: string permanent: boolean } // Initialize bloom filter from a generated JSON file const bloomFilter = ScalableBloomFilter.fromJSON(GeneratedBloomFilter as any) export async function middleware(request: NextRequest) { // Get the path for the incoming request const pathname = request.nextUrl.pathname // Check if the path is in the bloom filter if (bloomFilter.has(pathname)) { // Forward the pathname to the Route Handler const api = new URL( `/api/redirects?pathname=${encodeURIComponent(request.nextUrl.pathname)}`, request.nextUrl.origin ) try { // Fetch redirect data from the Route Handler const redirectData = await fetch(api) if (redirectData.ok) { const redirectEntry: RedirectEntry | undefined = await redirectData.json() if (redirectEntry) { // Determine the status code const statusCode = redirectEntry.permanent ? 308 : 307 // Redirect to the destination return NextResponse.redirect(redirectEntry.destination, statusCode) } } } catch (error) { console.error(error) } } // No redirect found, continue the request without redirecting return NextResponse.next() } Then, in the Route Handler: app/redirects/route.ts TypeScript JavaScriptTypeScript import { NextRequest, NextResponse } from 'next/server' import redirects from '@/app/redirects/redirects.json' type RedirectEntry = { destination: string permanent: boolean } export function GET(request: NextRequest) { const pathname = request.nextUrl.searchParams.get('pathname') if (!pathname) { return new Response('Bad Request', { status: 400 }) } // Get the redirect entry from the redirects.json file const redirect = (redirects as Record<string, RedirectEntry>)[pathname] // Account for bloom filter false positives if (!redirect) { return new Response('No redirect', { status: 400 }) } // Return the redirect entry return NextResponse.json(redirect) } > **Good to know:** > > * To generate a bloom filter, you can use a library like [`bloom-filters`](https://www.npmjs.com/package/bloom-filters). > * You should validate requests made to your Route Handler to prevent malicious requests. Next Steps ---------- [ App Router ... Functions ### redirect API Reference for the redirect function. ](/docs/app/api-reference/functions/redirect)[ App Router ... Functions ### permanentRedirect API Reference for the permanentRedirect function. ](/docs/app/api-reference/functions/permanentRedirect)[ App Router ... Routing ### Middleware Learn how to use Middleware to run code before a request is completed. ](/docs/app/building-your-application/routing/middleware)[ App Router ... next.config.js Options ### redirects Add redirects to your Next.js app. ](/docs/app/api-reference/next-config-js/redirects) [Previous Error Handling ](/docs/app/building-your-application/routing/error-handling) [Next Route Groups ](/docs/app/building-your-application/routing/route-groups) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"fd6fbff43cf6a7345d35b20b9958265f\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/typescript
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [ TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [New Projects](#new-projects) * [Existing Projects](#existing-projects) * [TypeScript Plugin](#typescript-plugin) * [Plugin Features](#plugin-features) * [Minimum TypeScript Version](#minimum-typescript-version) * [Statically Typed Links](#statically-typed-links) * [End-to-End Type Safety](#end-to-end-type-safety) * [Async Server Component TypeScript Error](#async-server-component-typescript-error) * [Passing Data Between Server & Client Components](#passing-data-between-server--client-components) * [Path aliases and baseUrl](#path-aliases-and-baseurl) * [Type checking next.config.js](#type-checking-nextconfigjs) * [Incremental type checking](#incremental-type-checking) * [Ignoring TypeScript Errors](#ignoring-typescript-errors) * [Custom Type Declarations](#custom-type-declarations) * [Version Changes](#version-changes) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/01-typescript.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)TypeScript TypeScript ========== Next.js provides a TypeScript-first development experience for building your React application. It comes with built-in TypeScript support for automatically installing the necessary packages and configuring the proper settings. As well as a [TypeScript Plugin](#typescript-plugin) for your editor. > **🎥 Watch:** Learn about the built-in TypeScript plugin → [YouTube (3 minutes)](https://www.youtube.com/watch?v=pqMqn9fKEf8) [New Projects](#new-projects) ----------------------------- `create-next-app` now ships with TypeScript by default. Terminal npx create-next-app@latest [Existing Projects](#existing-projects) --------------------------------------- Add TypeScript to your project by renaming a file to `.ts` / `.tsx`. Run `next dev` and `next build` to automatically install the necessary dependencies and add a `tsconfig.json` file with the recommended config options. If you already had a `jsconfig.json` file, copy the `paths` compiler option from the old `jsconfig.json` into the new `tsconfig.json` file, and delete the old `jsconfig.json` file. [TypeScript Plugin](#typescript-plugin) --------------------------------------- Next.js includes a custom TypeScript plugin and type checker, which VSCode and other code editors can use for advanced type-checking and auto-completion. You can enable the plugin in VS Code by: 1. Opening the command palette (`Ctrl/⌘` + `Shift` + `P`) 2. Searching for "TypeScript: Select TypeScript Version" 3. Selecting "Use Workspace Version" ![TypeScript Command Palette](/_next/image?url=%2Fdocs%2Flight%2Ftypescript-command-palette.png&w=3840&q=75)![TypeScript Command Palette](/_next/image?url=%2Fdocs%2Fdark%2Ftypescript-command-palette.png&w=3840&q=75) Now, when editing files, the custom plugin will be enabled. When running `next build`, the custom type checker will be used. ### [Plugin Features](#plugin-features) The TypeScript plugin can help with: * Warning if the invalid values for [segment config options](/docs/app/api-reference/file-conventions/route-segment-config) are passed. * Showing available options and in-context documentation. * Ensuring the `use client` directive is used correctly. * Ensuring client hooks (like `useState`) are only used in Client Components. > **Good to know**: More features will be added in the future. [Minimum TypeScript Version](#minimum-typescript-version) --------------------------------------------------------- It is highly recommended to be on at least `v4.5.2` of TypeScript to get syntax features such as [type modifiers on import names](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#type-on-import-names) and [performance improvements](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#real-path-sync-native). [Statically Typed Links](#statically-typed-links) ------------------------------------------------- Next.js can statically type links to prevent typos and other errors when using `next/link`, improving type safety when navigating between pages. To opt-into this feature, `experimental.typedRoutes` need to be enabled and the project needs to be using TypeScript. next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { typedRoutes: true, }, } module.exports = nextConfig Next.js will generate a link definition in `.next/types` that contains information about all existing routes in your application, which TypeScript can then use to provide feedback in your editor about invalid links. Currently, experimental support includes any string literal, including dynamic segments. For non-literal strings, you currently need to manually cast the `href` with `as Route`: import type { Route } from 'next'; import Link from 'next/link' // No TypeScript errors if href is a valid route <Link href="/about" /> <Link href="/blog/nextjs" /> <Link href={`/blog/${slug}`} /> <Link href={('/blog' + slug) as Route} /> // TypeScript errors if href is not a valid route <Link href="/aboot" /> To accept `href` in a custom component wrapping `next/link`, use a generic: import type { Route } from 'next' import Link from 'next/link' function Card<T extends string>({ href }: { href: Route<T> | URL }) { return ( <Link href={href}> <div>My Card</div> </Link> ) } > **How does it work?** > > When running `next dev` or `next build`, Next.js generates a hidden `.d.ts` file inside `.next` that contains information about all existing routes in your application (all valid routes as the `href` type of `Link`). This `.d.ts` file is included in `tsconfig.json` and the TypeScript compiler will check that `.d.ts` and provide feedback in your editor about invalid links. [End-to-End Type Safety](#end-to-end-type-safety) ------------------------------------------------- The Next.js App Router has **enhanced type safety**. This includes: 1. **No serialization of data between fetching function and page**: You can `fetch` directly in components, layouts, and pages on the server. This data _does not_ need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since `app` uses Server Components by default, we can use values like `Date`, `Map`, `Set`, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types. 2. **Streamlined data flow between components**: With the removal of `_app` in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual `pages` and `_app` were difficult to type and could introduce confusing bugs. With [colocated data fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) in the App Router, this is no longer an issue. [Data Fetching in Next.js](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection. We're able to type the response data as you would expect with normal TypeScript. For example: app/page.tsx async function getData() { const res = await fetch('https://api.example.com/...') // The return value is *not* serialized // You can return Date, Map, Set, etc. return res.json() } export default async function Page() { const name = await getData() return '...' } For _complete_ end-to-end type safety, this also requires your database or content provider to support TypeScript. This could be through using an [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) or type-safe query builder. [Async Server Component TypeScript Error](#async-server-component-typescript-error) ----------------------------------------------------------------------------------- To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher. If you are using an older version of TypeScript, you may see a `'Promise<Element>' is not a valid JSX element` type error. Updating to the latest version of TypeScript and `@types/react` should resolve this issue. [Passing Data Between Server & Client Components](#passing-data-between-server--client-components) -------------------------------------------------------------------------------------------------- When passing data between a Server and Client Component through props, the data is still serialized (converted to a string) for use in the browser. However, it does not need a special type. It’s typed the same as passing any other props between components. Further, there is less code to be serialized, as un-rendered data does not cross between the server and client (it remains on the server). This is only now possible through support for Server Components. [Path aliases and baseUrl](#path-aliases-and-baseurl) ----------------------------------------------------- Next.js automatically supports the `tsconfig.json` `"paths"` and `"baseUrl"` options. You can learn more about this feature on the [Module Path aliases documentation](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases). [Type checking next.config.js](#type-checking-nextconfigjs) ----------------------------------------------------------- The `next.config.js` file must be a JavaScript file as it does not get parsed by Babel or TypeScript, however you can add some type checking in your IDE using JSDoc as below: // @ts-check /** * @type {import('next').NextConfig} **/ const nextConfig = { /* config options here */ } module.exports = nextConfig [Incremental type checking](#incremental-type-checking) ------------------------------------------------------- Since `v10.2.1` Next.js supports [incremental type checking](https://www.typescriptlang.org/tsconfig#incremental) when enabled in your `tsconfig.json`, this can help speed up type checking in larger applications. [Ignoring TypeScript Errors](#ignoring-typescript-errors) --------------------------------------------------------- Next.js fails your **production build** (`next build`) when TypeScript errors are present in your project. If you'd like Next.js to dangerously produce production code even when your application has errors, you can disable the built-in type checking step. If disabled, be sure you are running type checks as part of your build or deploy process, otherwise this can be very dangerous. Open `next.config.js` and enable the `ignoreBuildErrors` option in the `typescript` config: next.config.js module.exports = { typescript: { // !! WARN !! // Dangerously allow production builds to successfully complete even if // your project has type errors. // !! WARN !! ignoreBuildErrors: true, }, } [Custom Type Declarations](#custom-type-declarations) ----------------------------------------------------- When you need to declare custom types, you might be tempted to modify `next-env.d.ts`. However, this file is automatically generated, so any changes you make will be overwritten. Instead, you should create a new file, let's call it `new-types.d.ts`, and reference it in your `tsconfig.json`: tsconfig.json { "compilerOptions": { "skipLibCheck": true //...truncated... }, "include": [ "new-types.d.ts", "next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx" ], "exclude": ["node_modules"] } [Version Changes](#version-changes) ----------------------------------- Version Changes `v13.2.0` Statically typed links are available in beta. `v12.0.0` [SWC](/docs/architecture/nextjs-compiler) is now used by default to compile TypeScript and TSX for faster builds. `v10.2.1` [Incremental type checking](https://www.typescriptlang.org/tsconfig#incremental) support added when enabled in your `tsconfig.json`. [Previous Configuring ](/docs/app/building-your-application/configuring) [Next ESLint ](/docs/app/building-your-application/configuring/eslint) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e1f757a1b82ab36a588c9064e92edbe8\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/images
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [ Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Usage](#usage) * [Local Images](#local-images) * [Remote Images](#remote-images) * [Domains](#domains) * [Loaders](#loaders) * [Priority](#priority) * [Image Sizing](#image-sizing) * [Styling](#styling) * [Examples](#examples) * [Responsive](#responsive) * [Fill Container](#fill-container) * [Background Image](#background-image) * [Other Properties](#other-properties) * [Configuration](#configuration) * [API Reference](#api-reference) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/01-images.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Images Image Optimization ================== Examples * [Image Component](https://github.com/vercel/next.js/tree/canary/examples/image-component) According to [Web Almanac](https://almanac.httparchive.org), images account for a huge portion of the typical website’s [page weight](https://almanac.httparchive.org/en/2022/page-weight#content-type-and-file-formats) and can have a sizable impact on your website's [LCP performance](https://almanac.httparchive.org/en/2022/performance#lcp-image-optimization). The Next.js Image component extends the HTML `<img>` element with features for automatic image optimization: * **Size Optimization:** Automatically serve correctly sized images for each device, using modern image formats like WebP and AVIF. * **Visual Stability:** Prevent [layout shift](/learn/seo/web-performance/cls) automatically when images are loading. * **Faster Page Loads:** Images are only loaded when they enter the viewport using native browser lazy loading, with optional blur-up placeholders. * **Asset Flexibility:** On-demand image resizing, even for images stored on remote servers > **🎥 Watch:** Learn more about how to use `next/image` → [YouTube (9 minutes)](https://youtu.be/IU_qq_c_lKA). [Usage](#usage) --------------- import Image from 'next/image' You can then define the `src` for your image (either local or remote). ### [Local Images](#local-images) To use a local image, `import` your `.jpg`, `.png`, or `.webp` image files. Next.js will [automatically determine](#image-sizing) the `width` and `height` of your image based on the imported file. These values are used to prevent [Cumulative Layout Shift](https://nextjs.org/learn/seo/web-performance/cls) while your image is loading. app/page.js import Image from 'next/image' import profilePic from './me.png' export default function Page() { return ( <Image src={profilePic} alt="Picture of the author" // width={500} automatically provided // height={500} automatically provided // blurDataURL="data:..." automatically provided // placeholder="blur" // Optional blur-up while loading /> ) } > **Warning:** Dynamic `await import()` or `require()` are _not_ supported. The `import` must be static so it can be analyzed at build time. ### [Remote Images](#remote-images) To use a remote image, the `src` property should be a URL string. Since Next.js does not have access to remote files during the build process, you'll need to provide the [`width`](/docs/app/api-reference/components/image#width), [`height`](/docs/app/api-reference/components/image#height) and optional [`blurDataURL`](/docs/app/api-reference/components/image#blurdataurl) props manually. The `width` and `height` attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in. The `width` and `height` do _not_ determine the rendered size of the image file. Learn more about [Image Sizing](#image-sizing). app/page.js 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} /> ) } To safely allow optimizing images, define a list of supported URL patterns in `next.config.js`. Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket: next.config.js module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 's3.amazonaws.com', port: '', pathname: '/my-bucket/**', }, ], }, } Learn more about [`remotePatterns`](/docs/app/api-reference/components/image#remotepatterns) configuration. If you want to use relative URLs for the image `src`, use a [`loader`](/docs/app/api-reference/components/image#loader). ### [Domains](#domains) Sometimes you may want to optimize a remote image, but still use the built-in Next.js Image Optimization API. To do this, leave the `loader` at its default setting and enter an absolute URL for the Image `src` prop. To protect your application from malicious users, you must define a list of remote hostnames you intend to use with the `next/image` component. > Learn more about [`remotePatterns`](/docs/app/api-reference/components/image#remotepatterns) configuration. ### [Loaders](#loaders) Note that in the [example earlier](#local-images), a partial URL (`"/me.png"`) is provided for a local image. This is possible because of the loader architecture. A loader is a function that generates the URLs for your image. It modifies the provided `src`, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic [srcset](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/srcset) generation, so that visitors to your site will be served an image that is the right size for their viewport. The default loader for Next.js applications uses the built-in Image Optimization API, which optimizes images from anywhere on the web, and then serves them directly from the Next.js web server. If you would like to serve your images directly from a CDN or image server, you can write your own loader function with a few lines of JavaScript. You can define a loader per-image with the [`loader` prop](/docs/app/api-reference/components/image#loader), or at the application level with the [`loaderFile` configuration](/docs/app/api-reference/components/image#loaderfile). [Priority](#priority) --------------------- You should add the `priority` property to the image that will be the [Largest Contentful Paint (LCP) element](https://web.dev/lcp/#what-elements-are-considered) for each page. Doing so allows Next.js to specially prioritize the image for loading (e.g. through preload tags or priority hints), leading to a meaningful boost in LCP. The LCP element is typically the largest image or text block visible within the viewport of the page. When you run `next dev`, you'll see a console warning if the LCP element is an `<Image>` without the `priority` property. Once you've identified the LCP image, you can add the property like this: app/page.js import Image from 'next/image' import profilePic from '../public/me.png' export default function Page() { return <Image src={profilePic} alt="Picture of the author" priority /> } See more about priority in the [`next/image` component documentation](/docs/app/api-reference/components/image#priority). [Image Sizing](#image-sizing) ----------------------------- One of the ways that images most commonly hurt performance is through _layout shift_, where the image pushes other elements around on the page as it loads in. This performance problem is so annoying to users that it has its own Core Web Vital, called [Cumulative Layout Shift](https://web.dev/cls/). The way to avoid image-based layout shifts is to [always size your images](https://web.dev/optimize-cls/#images-without-dimensions). This allows the browser to reserve precisely enough space for the image before it loads. Because `next/image` is designed to guarantee good performance results, it cannot be used in a way that will contribute to layout shift, and **must** be sized in one of three ways: 1. Automatically, using a [static import](#local-images) 2. Explicitly, by including a [`width`](/docs/app/api-reference/components/image#width) and [`height`](/docs/app/api-reference/components/image#height) property 3. Implicitly, by using [fill](/docs/app/api-reference/components/image#fill) which causes the image to expand to fill its parent element. > **What if I don't know the size of my images?** > > If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do: > > **Use `fill`** > > The [`fill`](/docs/app/api-reference/components/image#fill) prop allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page along [`sizes`](/docs/app/api-reference/components/image#sizes) prop to match any media query break points. You can also use [`object-fit`](https://developer.mozilla.org/docs/Web/CSS/object-fit) with `fill`, `contain`, or `cover`, and [`object-position`](https://developer.mozilla.org/docs/Web/CSS/object-position) to define how the image should occupy that space. > > **Normalize your images** > > If you're serving images from a source that you control, consider modifying your image pipeline to normalize the images to a specific size. > > **Modify your API calls** > > If your application is retrieving image URLs using an API call (such as to a CMS), you may be able to modify the API call to return the image dimensions along with the URL. If none of the suggested methods works for sizing your images, the `next/image` component is designed to work well on a page alongside standard `<img>` elements. [Styling](#styling) ------------------- 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/building-your-application/styling/css-modules), a [global stylesheet](/docs/app/building-your-application/styling/css-modules#global-styles), etc. * You can also use the `style` prop to assign inline styles. * You cannot use [styled-jsx](/docs/app/building-your-application/styling/css-in-js) because it's scoped to the current component (unless you mark the style as `global`). * When using `fill`, the parent element must have `position: relative` * This is necessary for the proper rendering of the image element in that layout mode. * When using `fill`, the parent element must have `display: block` * This is the default for `<div>` elements but should be specified otherwise. [Examples](#examples) --------------------- ### [Responsive](#responsive) ![Responsive image filling the width and height of its parent container](/_next/image?url=%2Fdocs%2Flight%2Fresponsive-image.png&w=3840&q=75)![Responsive image filling the width and height of its parent container](/_next/image?url=%2Fdocs%2Fdark%2Fresponsive-image.png&w=3840&q=75) 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 style={{ width: '100%', height: 'auto', }} /> </div> ) } ### [Fill Container](#fill-container) ![Grid of images filling parent container width](/_next/image?url=%2Fdocs%2Flight%2Ffill-container.png&w=3840&q=75)![Grid of images filling parent container width](/_next/image?url=%2Fdocs%2Fdark%2Ffill-container.png&w=3840&q=75) 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', height: '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> ) } ### [Background Image](#background-image) ![Background image taking full width and height of page](/_next/image?url=%2Fdocs%2Flight%2Fbackground-image.png&w=3840&q=75)![Background image taking full width and height of page](/_next/image?url=%2Fdocs%2Fdark%2Fbackground-image.png&w=3840&q=75) 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', }} /> ) } For examples of the Image component used with the various styles, see the [Image Component Demo](https://image-component.nextjs.gallery). [Other Properties](#other-properties) ------------------------------------- [**View all properties available to the `next/image` component.**](/docs/app/api-reference/components/image) [Configuration](#configuration) ------------------------------- The `next/image` component and Next.js Image Optimization API can be configured in the [`next.config.js` file](/docs/app/api-reference/next-config-js). These configurations allow you to [enable remote images](/docs/app/api-reference/components/image#remotepatterns), [define custom image breakpoints](/docs/app/api-reference/components/image#devicesizes), [change caching behavior](/docs/app/api-reference/components/image#caching-behavior) and more. [**Read the full image configuration documentation for more information.**](/docs/app/api-reference/components/image#configuration-options) API Reference ------------- Learn more about the next/image API. [ App Router ... Components ### <Image> Optimize Images in your Next.js Application using the built-in \`next/image\` Component. ](/docs/app/api-reference/components/image) [Previous Optimizing ](/docs/app/building-your-application/optimizing) [Next Videos ](/docs/app/building-your-application/optimizing/videos) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"c829dbb05dd96bf59e236adf9e8652a8\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/route-groups
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [ Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Convention](#convention) * [Examples](#examples) * [Organize routes without affecting the URL path](#organize-routes-without-affecting-the-url-path) * [Opting specific segments into a layout](#opting-specific-segments-into-a-layout) * [Creating multiple root layouts](#creating-multiple-root-layouts) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/07-route-groups.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Route Groups Route Groups ============ In the `app` directory, nested folders are normally mapped to URL paths. However, you can mark a folder as a **Route Group** to prevent the folder from being included in the route's URL path. This allows you to organize your route segments and project files into logical groups without affecting the URL path structure. Route groups are useful for: * [Organizing routes into groups](#organize-routes-without-affecting-the-url-path) e.g. by site section, intent, or team. * Enabling [nested layouts](/docs/app/building-your-application/routing/pages-and-layouts) in the same route segment level: * [Creating multiple nested layouts in the same segment, including multiple root layouts](#creating-multiple-root-layouts) * [Adding a layout to a subset of routes in a common segment](#opting-specific-segments-into-a-layout) [Convention](#convention) ------------------------- A route group can be created by wrapping a folder's name in parenthesis: `(folderName)` [Examples](#examples) --------------------- ### [Organize routes without affecting the URL path](#organize-routes-without-affecting-the-url-path) To organize routes without affecting the URL, create a group to keep related routes together. The folders in parenthesis will be omitted from the URL (e.g. `(marketing)` or `(shop)`). ![Organizing Routes with Route Groups](/_next/image?url=%2Fdocs%2Flight%2Froute-group-organisation.png&w=3840&q=75)![Organizing Routes with Route Groups](/_next/image?url=%2Fdocs%2Fdark%2Froute-group-organisation.png&w=3840&q=75) Even though routes inside `(marketing)` and `(shop)` share the same URL hierarchy, you can create a different layout for each group by adding a `layout.js` file inside their folders. ![Route Groups with Multiple Layouts](/_next/image?url=%2Fdocs%2Flight%2Froute-group-multiple-layouts.png&w=3840&q=75)![Route Groups with Multiple Layouts](/_next/image?url=%2Fdocs%2Fdark%2Froute-group-multiple-layouts.png&w=3840&q=75) ### [Opting specific segments into a layout](#opting-specific-segments-into-a-layout) To opt specific routes into a layout, create a new route group (e.g. `(shop)`) and move the routes that share the same layout into the group (e.g. `account` and `cart`). The routes outside of the group will not share the layout (e.g. `checkout`). ![Route Groups with Opt-in Layouts](/_next/image?url=%2Fdocs%2Flight%2Froute-group-opt-in-layouts.png&w=3840&q=75)![Route Groups with Opt-in Layouts](/_next/image?url=%2Fdocs%2Fdark%2Froute-group-opt-in-layouts.png&w=3840&q=75) ### [Creating multiple root layouts](#creating-multiple-root-layouts) To create multiple [root layouts](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required), remove the top-level `layout.js` file, and add a `layout.js` file inside each route groups. This is useful for partitioning an application into sections that have a completely different UI or experience. The `<html>` and `<body>` tags need to be added to each root layout. ![Route Groups with Multiple Root Layouts](/_next/image?url=%2Fdocs%2Flight%2Froute-group-multiple-root-layouts.png&w=3840&q=75)![Route Groups with Multiple Root Layouts](/_next/image?url=%2Fdocs%2Fdark%2Froute-group-multiple-root-layouts.png&w=3840&q=75) In the example above, both `(marketing)` and `(shop)` have their own root layout. * * * > **Good to know**: > > * The naming of route groups has no special significance other than for organization. They do not affect the URL path. > * Routes that include a route group **should not** resolve to the same URL path as other routes. For example, since route groups don't affect URL structure, `(marketing)/about/page.js` and `(shop)/about/page.js` would both resolve to `/about` and cause an error. > * If you use multiple root layouts without a top-level `layout.js` file, your home `page.js` file should be defined in one of the route groups, For example: `app/(marketing)/page.js`. > * Navigating **across multiple root layouts** will cause a **full page load** (as opposed to a client-side navigation). For example, navigating from `/cart` that uses `app/(shop)/layout.js` to `/blog` that uses `app/(marketing)/layout.js` will cause a full page load. This **only** applies to multiple root layouts. [Previous Redirecting ](/docs/app/building-your-application/routing/redirecting) [Next Project Organization ](/docs/app/building-your-application/routing/colocation) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e0d3e1d0d45da72288b7de5d3604c39d\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/components/link
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [ <Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Props](#props) * [href (required)](#href-required) * [replace](#replace) * [scroll](#scroll) * [prefetch](#prefetch) * [Examples](#examples) * [Linking to Dynamic Routes](#linking-to-dynamic-routes) * [If the child is a custom component that wraps an <a> tag](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) * [If the child is a functional component](#if-the-child-is-a-functional-component) * [With URL Object](#with-url-object) * [Replace the URL instead of push](#replace-the-url-instead-of-push) * [Disable scrolling to the top of the page](#disable-scrolling-to-the-top-of-the-page) * [Middleware](#middleware) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/01-components/link.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Components](/docs/app/api-reference/components)<Link> <Link> ====== `<Link>` is a React component that extends the HTML `<a>` element to provide [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) and client-side navigation between routes. It is the primary way to navigate between routes in Next.js. app/page.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Page() { return <Link href="/dashboard">Dashboard</Link> } [Props](#props) --------------- Here's a summary of the props available for the Link Component: Prop Example Type Required [`href`](#href-required) `href="/dashboard"` String or Object Yes [`replace`](#replace) `replace={false}` Boolean \- [`scroll`](#scroll) `scroll={false}` Boolean \- [`prefetch`](#prefetch) `prefetch={false}` Boolean or null \- > **Good to know**: `<a>` tag attributes such as `className` or `target="_blank"` can be added to `<Link>` as props and will be passed to the underlying `<a>` element. ### [`href` (required)](#href-required) The path or URL to navigate to. <Link href="/dashboard">Dashboard</Link> `href` can also accept an object, for example: // Navigate to /about?name=test <Link href={{ pathname: '/about', query: { name: 'test' }, }} > About </Link> ### [`replace`](#replace) **Defaults to `false`.** When `true`, `next/link` will replace the current history state instead of adding a new URL into the [browser’s history](https://developer.mozilla.org/docs/Web/API/History_API) stack. app/page.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Page() { return ( <Link href="/dashboard" replace> Dashboard </Link> ) } ### [`scroll`](#scroll) **Defaults to `true`.** The default behavior of `<Link>` **is to scroll to the top of a new route or to maintain the scroll position for backwards and forwards navigation.** When `false`, `next/link` will _not_ scroll to the top of the page after a navigation. app/page.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Page() { return ( <Link href="/dashboard" scroll={false}> Dashboard </Link> ) } > **Good to know**: > > * Next.js will scroll to the [Page](/docs/app/building-your-application/routing/pages-and-layouts#pages) if it is not visible in the viewport upon navigation. ### [`prefetch`](#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 background to improve the performance of client-side navigations. Prefetching is only enabled in production. * **`null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) boundary will be prefetched. * `true`: The full route will be prefetched for both static and dynamic routes. * `false`: Prefetching will never happen both on entering the viewport and on hover. app/page.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Page() { return ( <Link href="/dashboard" prefetch={false}> Dashboard </Link> ) } [Examples](#examples) --------------------- ### [Linking to Dynamic Routes](#linking-to-dynamic-routes) For dynamic routes, it can be handy to use template literals to create the link's path. For example, you can generate a list of links to the dynamic route `app/blog/[slug]/page.js`: app/blog/page.js import Link from 'next/link' function Page({ posts }) { return ( <ul> {posts.map((post) => ( <li key={post.id}> <Link href={`/blog/${post.slug}`}>{post.title}</Link> </li> ))} </ul> ) } ### [If the child is a custom component that wraps an `<a>` tag](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) If the child of `Link` is a custom component that wraps an `<a>` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `<a>` tag will not have the `href` attribute, which hurts your site's accessibility and might affect SEO. If you're using [ESLint](/docs/app/building-your-application/configuring/eslint#eslint-plugin), there is a built-in rule `next/link-passhref` to ensure correct usage of `passHref`. import Link from 'next/link' import styled from 'styled-components' // This creates a custom component that wraps an <a> tag const RedLink = styled.a` color: red; ` function NavLink({ href, name }) { return ( <Link href={href} passHref legacyBehavior> <RedLink>{name}</RedLink> </Link> ) } export default NavLink * If you’re using [emotion](https://emotion.sh/)’s JSX pragma feature (`@jsx jsx`), you must use `passHref` even if you use an `<a>` tag directly. * The component should support `onClick` property to trigger navigation correctly ### [If the child is a functional component](#if-the-child-is-a-functional-component) If the child of `Link` is a functional component, in addition to using `passHref` and `legacyBehavior`, you must wrap the component in [`React.forwardRef`](https://react.dev/reference/react/forwardRef): import Link from 'next/link' // `onClick`, `href`, and `ref` need to be passed to the DOM element // for proper handling const MyButton = React.forwardRef(({ onClick, href }, ref) => { return ( <a href={href} onClick={onClick} ref={ref}> Click Me </a> ) }) function Home() { return ( <Link href="/about" passHref legacyBehavior> <MyButton /> </Link> ) } export default Home ### [With URL Object](#with-url-object) `Link` can also receive a URL object and it will automatically format it to create the URL string. Here's how to do it: import Link from 'next/link' function Home() { return ( <ul> <li> <Link href={{ pathname: '/about', query: { name: 'test' }, }} > About us </Link> </li> <li> <Link href={{ pathname: '/blog/[slug]', query: { slug: 'my-post' }, }} > Blog Post </Link> </li> </ul> ) } export default Home The above example has a link to: * A predefined route: `/about?name=test` * A [dynamic route](/docs/app/building-your-application/routing/dynamic-routes): `/blog/my-post` You can use every property as defined in the [Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects). ### [Replace the URL instead of push](#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: <Link href="/about" replace> About us </Link> ### [Disable scrolling to the top of the page](#disable-scrolling-to-the-top-of-the-page) The default behavior of `Link` is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, like a normal `<a>` tag. To prevent scrolling to the top / hash `scroll={false}` can be added to `Link`: <Link href="/#hashid" scroll={false}> Disables scrolling to the top </Link> ### [Middleware](#middleware) It's common to use [Middleware](/docs/app/building-your-application/routing/middleware) for authentication or other purposes that involve rewriting the user to a different page. In order for the `<Link />` component to properly prefetch links with rewrites via Middleware, you need to tell Next.js both the URL to display and the URL to prefetch. This is required to avoid un-necessary fetches to middleware to know the correct route to prefetch. For example, if you want to serve a `/dashboard` route that has authenticated and visitor views, you may add something similar to the following in your Middleware to redirect the user to the correct page: middleware.js export function middleware(req) { const nextUrl = req.nextUrl if (nextUrl.pathname === '/dashboard') { if (req.cookies.authToken) { return NextResponse.rewrite(new URL('/auth/dashboard', req.url)) } else { return NextResponse.rewrite(new URL('/public/dashboard', req.url)) } } } In this case, you would want to use the following code in your `<Link />` component: import Link from 'next/link' import useIsAuthed from './hooks/useIsAuthed' export default function Page() { const isAuthed = useIsAuthed() const path = isAuthed ? '/auth/dashboard' : '/public/dashboard' return ( <Link as="/dashboard" href={path}> Dashboard </Link> ) } [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` No longer requires a child `<a>` tag. A [codemod](/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components) is provided to automatically update your codebase. `v10.0.0` `href` props pointing to a dynamic route are automatically resolved and no longer require an `as` prop. `v8.0.0` Improved prefetching performance. `v1.0.0` `next/link` introduced. [Previous <Image> ](/docs/app/api-reference/components/image) [Next <Script> ](/docs/app/api-reference/components/script) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"6ebde593d816c145c735f906f953c6bf\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/eslint
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [ESLint Config](#eslint-config) * [ESLint Plugin](#eslint-plugin) * [Custom Settings](#custom-settings) * [rootDir](#rootdir) * [Linting Custom Directories and Files](#linting-custom-directories-and-files) * [Caching](#caching) * [Disabling Rules](#disabling-rules) * [Core Web Vitals](#core-web-vitals) * [Usage With Other Tools](#usage-with-other-tools) * [Prettier](#prettier) * [lint-staged](#lint-staged) * [Migrating Existing Config](#migrating-existing-config) * [Recommended Plugin Ruleset](#recommended-plugin-ruleset) * [Additional Configurations](#additional-configurations) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/02-eslint.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)ESLint ESLint ====== Next.js provides an integrated [ESLint](https://eslint.org/) experience out of the box. Add `next lint` as a script to `package.json`: package.json { "scripts": { "lint": "next lint" } } Then run `npm run lint` or `yarn lint`: Terminal yarn lint If you don't already have ESLint configured in your application, you will be guided through the installation and configuration process. Terminal yarn lint > You'll see a prompt like this: > > ? How would you like to configure ESLint? > > ❯ Strict (recommended) > Base > Cancel One of the following three options can be selected: * **Strict**: Includes Next.js' base ESLint configuration along with a stricter [Core Web Vitals rule-set](#core-web-vitals). This is the recommended configuration for developers setting up ESLint for the first time. .eslintrc.json { "extends": "next/core-web-vitals" } * **Base**: Includes Next.js' base ESLint configuration. .eslintrc.json { "extends": "next" } * **Cancel**: Does not include any ESLint configuration. Only select this option if you plan on setting up your own custom ESLint configuration. If either of the two configuration options are selected, Next.js will automatically install `eslint` and `eslint-config-next` as dependencies in your application and create an `.eslintrc.json` file in the root of your project that includes your selected configuration. You can now run `next lint` every time you want to run ESLint to catch errors. Once ESLint has been set up, it will also automatically run during every build (`next build`). Errors will fail the build, while warnings will not. > If you do not want ESLint to run during `next build`, refer to the documentation for [Ignoring ESLint](/docs/app/api-reference/next-config-js/eslint). We recommend using an appropriate [integration](https://eslint.org/docs/user-guide/integrations#editors) to view warnings and errors directly in your code editor during development. [ESLint Config](#eslint-config) ------------------------------- The default configuration (`eslint-config-next`) includes everything you need to have an optimal out-of-the-box linting experience in Next.js. If you do not have ESLint already configured in your application, we recommend using `next lint` to set up ESLint along with this configuration. > If you would like to use `eslint-config-next` along with other ESLint configurations, refer to the [Additional Configurations](#additional-configurations) section to learn how to do so without causing any conflicts. Recommended rule-sets from the following ESLint plugins are all used within `eslint-config-next`: * [`eslint-plugin-react`](https://www.npmjs.com/package/eslint-plugin-react) * [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) * [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next) This will take precedence over the configuration from `next.config.js`. [ESLint Plugin](#eslint-plugin) ------------------------------- Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next), already bundled within the base configuration that makes it possible to catch common issues and problems in a Next.js application. The full set of rules is as follows: Enabled in the recommended configuration Rule Description [@next/next/google-font-display](/docs/messages/google-font-display) Enforce font-display behavior with Google Fonts. [@next/next/google-font-preconnect](/docs/messages/google-font-preconnect) Ensure `preconnect` is used with Google Fonts. [@next/next/inline-script-id](/docs/messages/inline-script-id) Enforce `id` attribute on `next/script` components with inline content. [@next/next/next-script-for-ga](/docs/messages/next-script-for-ga) Prefer `next/script` component when using the inline script for Google Analytics. [@next/next/no-assign-module-variable](/docs/messages/no-assign-module-variable) Prevent assignment to the `module` variable. [@next/next/no-async-client-component](/docs/messages/no-async-client-component) Prevent client components from being async functions. [@next/next/no-before-interactive-script-outside-document](/docs/messages/no-before-interactive-script-outside-document) Prevent usage of `next/script`'s `beforeInteractive` strategy outside of `pages/_document.js`. [@next/next/no-css-tags](/docs/messages/no-css-tags) Prevent manual stylesheet tags. [@next/next/no-document-import-in-page](/docs/messages/no-document-import-in-page) Prevent importing `next/document` outside of `pages/_document.js`. [@next/next/no-duplicate-head](/docs/messages/no-duplicate-head) Prevent duplicate usage of `<Head>` in `pages/_document.js`. [@next/next/no-head-element](/docs/messages/no-head-element) Prevent usage of `<head>` element. [@next/next/no-head-import-in-document](/docs/messages/no-head-import-in-document) Prevent usage of `next/head` in `pages/_document.js`. [@next/next/no-html-link-for-pages](/docs/messages/no-html-link-for-pages) Prevent usage of `<a>` elements to navigate to internal Next.js pages. [@next/next/no-img-element](/docs/messages/no-img-element) Prevent usage of `<img>` element due to slower LCP and higher bandwidth. [@next/next/no-page-custom-font](/docs/messages/no-page-custom-font) Prevent page-only custom fonts. [@next/next/no-script-component-in-head](/docs/messages/no-script-component-in-head) Prevent usage of `next/script` in `next/head` component. [@next/next/no-styled-jsx-in-document](/docs/messages/no-styled-jsx-in-document) Prevent usage of `styled-jsx` in `pages/_document.js`. [@next/next/no-sync-scripts](/docs/messages/no-sync-scripts) Prevent synchronous scripts. [@next/next/no-title-in-document-head](/docs/messages/no-title-in-document-head) Prevent usage of `<title>` with `Head` component from `next/document`. @next/next/no-typos Prevent common typos in [Next.js's data fetching functions](/docs/pages/building-your-application/data-fetching) [@next/next/no-unwanted-polyfillio](/docs/messages/no-unwanted-polyfillio) Prevent duplicate polyfills from Polyfill.io. If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including `eslint-config-next` unless a few conditions are met. Refer to the [Recommended Plugin Ruleset](#recommended-plugin-ruleset) to learn more. ### [Custom Settings](#custom-settings) #### [`rootDir`](#rootdir) If you're using `eslint-plugin-next` in a project where Next.js isn't installed in your root directory (such as a monorepo), you can tell `eslint-plugin-next` where to find your Next.js application using the `settings` property in your `.eslintrc`: .eslintrc.json { "extends": "next", "settings": { "next": { "rootDir": "packages/my-app/" } } } `rootDir` can be a path (relative or absolute), a glob (i.e. `"packages/*/"`), or an array of paths and/or globs. [Linting Custom Directories and Files](#linting-custom-directories-and-files) ----------------------------------------------------------------------------- By default, Next.js will run ESLint for all files in the `pages/`, `app/`, `components/`, `lib/`, and `src/` directories. However, you can specify which directories using the `dirs` option in the `eslint` config in `next.config.js` for production builds: next.config.js module.exports = { eslint: { dirs: ['pages', 'utils'], // Only run ESLint on the 'pages' and 'utils' directories during production builds (next build) }, } Similarly, the `--dir` and `--file` flags can be used for `next lint` to lint specific directories and files: Terminal next lint --dir pages --dir utils --file bar.js [Caching](#caching) ------------------- To improve performance, information of files processed by ESLint are cached by default. This is stored in `.next/cache` or in your defined [build directory](/docs/app/api-reference/next-config-js/distDir). If you include any ESLint rules that depend on more than the contents of a single source file and need to disable the cache, use the `--no-cache` flag with `next lint`. Terminal next lint --no-cache [Disabling Rules](#disabling-rules) ----------------------------------- If you would like to modify or disable any rules provided by the supported plugins (`react`, `react-hooks`, `next`), you can directly change them using the `rules` property in your `.eslintrc`: .eslintrc.json { "extends": "next", "rules": { "react/no-unescaped-entities": "off", "@next/next/no-page-custom-font": "off" } } ### [Core Web Vitals](#core-web-vitals) The `next/core-web-vitals` rule set is enabled when `next lint` is run for the first time and the **strict** option is selected. .eslintrc.json { "extends": "next/core-web-vitals" } `next/core-web-vitals` updates `eslint-plugin-next` to error on a number of rules that are warnings by default if they affect [Core Web Vitals](https://web.dev/vitals/). > The `next/core-web-vitals` entry point is automatically included for new applications built with [Create Next App](/docs/app/api-reference/create-next-app). [Usage With Other Tools](#usage-with-other-tools) ------------------------------------------------- ### [Prettier](#prettier) ESLint also contains code formatting rules, which can conflict with your existing [Prettier](https://prettier.io/) setup. We recommend including [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) in your ESLint config to make ESLint and Prettier work together. First, install the dependency: Terminal npm install --save-dev eslint-config-prettier yarn add --dev eslint-config-prettier pnpm add --save-dev eslint-config-prettier bun add --dev eslint-config-prettier Then, add `prettier` to your existing ESLint config: .eslintrc.json { "extends": ["next", "prettier"] } ### [lint-staged](#lint-staged) If you would like to use `next lint` with [lint-staged](https://github.com/okonet/lint-staged) to run the linter on staged git files, you'll have to add the following to the `.lintstagedrc.js` file in the root of your project in order to specify usage of the `--file` flag. .lintstagedrc.js const path = require('path') const buildEslintCommand = (filenames) => `next lint --fix --file ${filenames .map((f) => path.relative(process.cwd(), f)) .join(' --file ')}` module.exports = { '*.{js,jsx,ts,tsx}': [buildEslintCommand], } [Migrating Existing Config](#migrating-existing-config) ------------------------------------------------------- ### [Recommended Plugin Ruleset](#recommended-plugin-ruleset) If you already have ESLint configured in your application and any of the following conditions are true: * You have one or more of the following plugins already installed (either separately or through a different config such as `airbnb` or `react-app`): * `react` * `react-hooks` * `jsx-a11y` * `import` * You've defined specific `parserOptions` that are different from how Babel is configured within Next.js (this is not recommended unless you have [customized your Babel configuration](/docs/pages/building-your-application/configuring/babel)) * You have `eslint-plugin-import` installed with Node.js and/or TypeScript [resolvers](https://github.com/benmosher/eslint-plugin-import#resolvers) defined to handle imports Then we recommend either removing these settings if you prefer how these properties have been configured within [`eslint-config-next`](https://github.com/vercel/next.js/blob/canary/packages/eslint-config-next/index.js) or extending directly from the Next.js ESLint plugin instead: module.exports = { extends: [ //... 'plugin:@next/next/recommended', ], } The plugin can be installed normally in your project without needing to run `next lint`: Terminal npm install --save-dev @next/eslint-plugin-next yarn add --dev @next/eslint-plugin-next pnpm add --save-dev @next/eslint-plugin-next bun add --dev @next/eslint-plugin-next This eliminates the risk of collisions or errors that can occur due to importing the same plugin or parser across multiple configurations. ### [Additional Configurations](#additional-configurations) If you already use a separate ESLint configuration and want to include `eslint-config-next`, ensure that it is extended last after other configurations. For example: .eslintrc.json { "extends": ["eslint:recommended", "next"] } The `next` configuration already handles setting default values for the `parser`, `plugins` and `settings` properties. There is no need to manually re-declare any of these properties unless you need a different configuration for your use case. If you include any other shareable configurations, **you will need to make sure that these properties are not overwritten or modified**. Otherwise, we recommend removing any configurations that share behavior with the `next` configuration or extending directly from the Next.js ESLint plugin as mentioned above. [Previous TypeScript ](/docs/app/building-your-application/configuring/typescript) [Next Environment Variables ](/docs/app/building-your-application/configuring/environment-variables) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"6d946d1212ca7b2ac838b09b6a1e278c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/not-found
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [ notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [notFound()](#notfound) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/not-found.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)notFound notFound ======== The `notFound` function allows you to render the [`not-found file`](/docs/app/api-reference/file-conventions/not-found) within a route segment as well as inject a `<meta name="robots" content="noindex" />` tag. [`notFound()`](#notfound) ------------------------- Invoking the `notFound()` function throws a `NEXT_NOT_FOUND` error and terminates rendering of the route segment in which it was thrown. Specifying a [**not-found** file](/docs/app/api-reference/file-conventions/not-found) allows you to gracefully handle such errors by rendering a Not Found UI within the segment. app/user/\[id\]/page.js import { notFound } from 'next/navigation' async function fetchUser(id) { const res = await fetch('https://...') if (!res.ok) return undefined return res.json() } export default async function Profile({ params }) { const user = await fetchUser(params.id) if (!user) { notFound() } // ... } > **Good to know**: `notFound()` does not require you to use `return notFound()` due to using the TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) type. [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `notFound` introduced. [Previous NextResponse ](/docs/app/api-reference/functions/next-response) [Next permanentRedirect ](/docs/app/api-reference/functions/permanentRedirect) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"d23192c35ba9117245ca7402b173735a\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/next-response
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [ NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [cookies](#cookies) * [set(name, value)](#setname-value) * [get(name)](#getname) * [getAll()](#getall) * [delete(name)](#deletename) * [json()](#json) * [redirect()](#redirect) * [rewrite()](#rewrite) * [next()](#next) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/next-response.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)NextResponse NextResponse ============ NextResponse extends the [Web Response API](https://developer.mozilla.org/docs/Web/API/Response) with additional convenience methods. [`cookies`](#cookies) --------------------- Read or mutate the [`Set-Cookie`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie) header of the response. ### [`set(name, value)`](#setname-value) Given a name, set a cookie with the given value on the response. // Given incoming request /home let response = NextResponse.next() // Set a cookie to hide the banner response.cookies.set('show-banner', 'false') // Response will have a `Set-Cookie:show-banner=false;path=/home` header return response ### [`get(name)`](#getname) Given a cookie name, return the value of the cookie. If the cookie is not found, `undefined` is returned. If multiple cookies are found, the first one is returned. // Given incoming request /home let response = NextResponse.next() // { name: 'show-banner', value: 'false', Path: '/home' } response.cookies.get('show-banner') ### [`getAll()`](#getall) Given a cookie name, return the values of the cookie. If no name is given, return all cookies on the response. // Given incoming request /home let response = NextResponse.next() // [ // { name: 'experiments', value: 'new-pricing-page', Path: '/home' }, // { name: 'experiments', value: 'winter-launch', Path: '/home' }, // ] response.cookies.getAll('experiments') // Alternatively, get all cookies for the response response.cookies.getAll() ### [`delete(name)`](#deletename) Given a cookie name, delete the cookie from the response. // Given incoming request /home let response = NextResponse.next() // Returns true for deleted, false is nothing is deleted response.cookies.delete('experiments') [`json()`](#json) ----------------- Produce a response with the given JSON body. app/api/route.ts TypeScript JavaScriptTypeScript import { NextResponse } from 'next/server' export async function GET(request: Request) { return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }) } [`redirect()`](#redirect) ------------------------- Produce a response that redirects to a [URL](https://developer.mozilla.org/docs/Web/API/URL). import { NextResponse } from 'next/server' return NextResponse.redirect(new URL('/new', request.url)) The [URL](https://developer.mozilla.org/docs/Web/API/URL) can be created and modified before being used in the `NextResponse.redirect()` method. For example, you can use the `request.nextUrl` property to get the current URL, and then modify it to redirect to a different URL. import { NextResponse } from 'next/server' // Given an incoming request... const loginUrl = new URL('/login', request.url) // Add ?from=/incoming-url to the /login URL loginUrl.searchParams.set('from', request.nextUrl.pathname) // And redirect to the new URL return NextResponse.redirect(loginUrl) [`rewrite()`](#rewrite) ----------------------- Produce a response that rewrites (proxies) the given [URL](https://developer.mozilla.org/docs/Web/API/URL) while preserving the original URL. import { NextResponse } from 'next/server' // Incoming request: /about, browser shows /about // Rewritten request: /proxy, browser shows /about return NextResponse.rewrite(new URL('/proxy', request.url)) [`next()`](#next) ----------------- The `next()` method is useful for Middleware, as it allows you to return early and continue routing. import { NextResponse } from 'next/server' return NextResponse.next() You can also forward `headers` when producing the response: import { NextResponse } from 'next/server' // Given an incoming request... const newHeaders = new Headers(request.headers) // Add a new header newHeaders.set('x-version', '123') // And produce a response with the new headers return NextResponse.next({ request: { // New request headers headers: newHeaders, }, }) [Previous NextRequest ](/docs/app/api-reference/functions/next-request) [Next notFound ](/docs/app/api-reference/functions/not-found) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"f30ca16377a1cd58419d44d6fd545478\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [ Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Loading Environment Variables](#loading-environment-variables) * [Referencing Other Variables](#referencing-other-variables) * [Bundling Environment Variables for the Browser](#bundling-environment-variables-for-the-browser) * [Runtime Environment Variables](#runtime-environment-variables) * [Default Environment Variables](#default-environment-variables) * [Environment Variables on Vercel](#environment-variables-on-vercel) * [Test Environment Variables](#test-environment-variables) * [Environment Variable Load Order](#environment-variable-load-order) * [Good to know](#good-to-know) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/03-environment-variables.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)Environment Variables Environment Variables ===================== Examples * [Environment Variables](https://github.com/vercel/next.js/tree/canary/examples/environment-variables) Next.js comes with built-in support for environment variables, which allows you to do the following: * [Use `.env.local` to load environment variables](#loading-environment-variables) * [Bundle environment variables for the browser by prefixing with `NEXT_PUBLIC_`](#bundling-environment-variables-for-the-browser) [Loading Environment Variables](#loading-environment-variables) --------------------------------------------------------------- Next.js has built-in support for loading environment variables from `.env.local` into `process.env`. .env.local DB_HOST=localhost DB_USER=myuser DB_PASS=mypassword > **Note**: Next.js also supports multiline variables inside of your `.env*` files: > > # .env.local > > # you can write with line breaks > PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- > ... > Kh9NV... > ... > -----END DSA PRIVATE KEY-----" > > # or with `\n` inside double quotes > PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END DSA PRIVATE KEY-----\n" > **Note**: If you are using a `/src` folder, please note that Next.js will load the .env files **only** from the parent folder and **not** from the `/src` folder. This loads `process.env.DB_HOST`, `process.env.DB_USER`, and `process.env.DB_PASS` into the Node.js environment automatically allowing you to use them in [Route Handlers](/docs/app/building-your-application/routing/route-handlers). For example: app/api/route.js export async function GET() { const db = await myDB.connect({ host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS, }) // ... } ### [Referencing Other Variables](#referencing-other-variables) Next.js will automatically expand variables that use `$` to reference other variables e.g. `$VARIABLE` inside of your `.env*` files. This allows you to reference other secrets. For example: .env TWITTER_USER=nextjs TWITTER_URL=https://twitter.com/$TWITTER_USER In the above example, `process.env.TWITTER_URL` would be set to `https://twitter.com/nextjs`. > **Good to know**: If you need to use variable with a `$` in the actual value, it needs to be escaped e.g. `\$`. [Bundling Environment Variables for the Browser](#bundling-environment-variables-for-the-browser) ------------------------------------------------------------------------------------------------- Non-`NEXT_PUBLIC_` environment variables are only available in the Node.js environment, meaning they aren't accessible to the browser (the client runs in a different _environment_). In order to make the value of an environment variable accessible in the browser, Next.js can "inline" a value, at build time, into the js bundle that is delivered to the client, replacing all references to `process.env.[variable]` with a hard-coded value. To tell it to do this, you just have to prefix the variable with `NEXT_PUBLIC_`. For example: Terminal NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk This will tell Next.js to replace all references to `process.env.NEXT_PUBLIC_ANALYTICS_ID` in the Node.js environment with the value from the environment in which you run `next build`, allowing you to use it anywhere in your code. It will be inlined into any JavaScript sent to the browser. > **Note**: After being built, your app will no longer respond to changes to these environment variables. For instance, if you use a Heroku pipeline to promote slugs built in one environment to another environment, or if you build and deploy a single Docker image to multiple environments, all `NEXT_PUBLIC_` variables will be frozen with the value evaluated at build time, so these values need to be set appropriately when the project is built. If you need access to runtime environment values, you'll have to setup your own API to provide them to the client (either on demand or during initialization). pages/index.js import setupAnalyticsService from '../lib/my-analytics-service' // 'NEXT_PUBLIC_ANALYTICS_ID' can be used here as it's prefixed by 'NEXT_PUBLIC_'. // It will be transformed at build time to `setupAnalyticsService('abcdefghijk')`. setupAnalyticsService(process.env.NEXT_PUBLIC_ANALYTICS_ID) function HomePage() { return <h1>Hello World</h1> } export default HomePage Note that dynamic lookups will _not_ be inlined, such as: // This will NOT be inlined, because it uses a variable const varName = 'NEXT_PUBLIC_ANALYTICS_ID' setupAnalyticsService(process.env[varName]) // This will NOT be inlined, because it uses a variable const env = process.env setupAnalyticsService(env.NEXT_PUBLIC_ANALYTICS_ID) ### [Runtime Environment Variables](#runtime-environment-variables) Next.js can support both build time and runtime environment variables. **By default, environment variables are only available on the server**. To expose an environment variable to the browser, it must be prefixed with `NEXT_PUBLIC_`. However, these public environment variables will be inlined into the JavaScript bundle during `next build`. To read runtime environment variables, we recommend using `getServerSideProps` or [incrementally adopting the App Router](/docs/app/building-your-application/upgrading/app-router-migration). With the App Router, we can safely read environment variables on the server during dynamic rendering. This allows you to use a singular Docker image that can be promoted through multiple environments with different values. import { unstable_noStore as noStore } from 'next/cache' export default function Component() { noStore() // cookies(), headers(), and other dynamic functions // will also opt into dynamic rendering, meaning // this env variable is evaluated at runtime const value = process.env.MY_VALUE // ... } **Good to know:** * You can run code on server startup using the [`register` function](/docs/app/building-your-application/optimizing/instrumentation). * We do not recommend using the [runtimeConfig](/docs/pages/api-reference/next-config-js/runtime-configuration) option, as this does not work with the standalone output mode. Instead, we recommend [incrementally adopting](/docs/app/building-your-application/upgrading/app-router-migration) the App Router. [Default Environment Variables](#default-environment-variables) --------------------------------------------------------------- In general only one `.env.local` file is needed. However, sometimes you might want to add some defaults for the `development` (`next dev`) or `production` (`next start`) environment. Next.js allows you to set defaults in `.env` (all environments), `.env.development` (development environment), and `.env.production` (production environment). `.env.local` always overrides the defaults set. > **Good to know**: `.env`, `.env.development`, and `.env.production` files should be included in your repository as they define defaults. **`.env*.local` should be added to `.gitignore`**, as those files are intended to be ignored. `.env.local` is where secrets can be stored. [Environment Variables on Vercel](#environment-variables-on-vercel) ------------------------------------------------------------------- When deploying your Next.js application to [Vercel](https://vercel.com), Environment Variables can be configured [in the Project Settings](https://vercel.com/docs/projects/environment-variables?utm_medium=docs&utm_source=next-site&utm_campaign=next-website). All types of Environment Variables should be configured there. Even Environment Variables used in Development – which can be [downloaded onto your local device](https://vercel.com/docs/concepts/projects/environment-variables#development-environment-variables?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) afterwards. If you've configured [Development Environment Variables](https://vercel.com/docs/concepts/projects/environment-variables#development-environment-variables?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) you can pull them into a `.env.local` for usage on your local machine using the following command: Terminal vercel env pull .env.local > **Good to know**: When deploying your Next.js application to [Vercel](https://vercel.com), your environment variables in `.env*` files will not be made available to Edge Runtime, unless their name are prefixed with `NEXT_PUBLIC_`. We strongly recommend managing your environment variables in [Project Settings](https://vercel.com/docs/projects/environment-variables?utm_medium=docs&utm_source=next-site&utm_campaign=next-website) instead, from where all environment variables are available. [Test Environment Variables](#test-environment-variables) --------------------------------------------------------- Apart from `development` and `production` environments, there is a 3rd option available: `test`. In the same way you can set defaults for development or production environments, you can do the same with a `.env.test` file for the `testing` environment (though this one is not as common as the previous two). Next.js will not load environment variables from `.env.development` or `.env.production` in the `testing` environment. This one is useful when running tests with tools like `jest` or `cypress` where you need to set specific environment vars only for testing purposes. Test default values will be loaded if `NODE_ENV` is set to `test`, though you usually don't need to do this manually as testing tools will address it for you. There is a small difference between `test` environment, and both `development` and `production` that you need to bear in mind: `.env.local` won't be loaded, as you expect tests to produce the same results for everyone. This way every test execution will use the same env defaults across different executions by ignoring your `.env.local` (which is intended to override the default set). > **Good to know**: similar to Default Environment Variables, `.env.test` file should be included in your repository, but `.env.test.local` shouldn't, as `.env*.local` are intended to be ignored through `.gitignore`. While running unit tests you can make sure to load your environment variables the same way Next.js does by leveraging the `loadEnvConfig` function from the `@next/env` package. // The below can be used in a Jest global setup file or similar for your testing set-up import { loadEnvConfig } from '@next/env' export default async () => { const projectDir = process.cwd() loadEnvConfig(projectDir) } [Environment Variable Load Order](#environment-variable-load-order) ------------------------------------------------------------------- Environment variables are looked up in the following places, in order, stopping once the variable is found. 1. `process.env` 2. `.env.$(NODE_ENV).local` 3. `.env.local` (Not checked when `NODE_ENV` is `test`.) 4. `.env.$(NODE_ENV)` 5. `.env` For example, if `NODE_ENV` is `development` and you define a variable in both `.env.development.local` and `.env`, the value in `.env.development.local` will be used. > **Good to know**: The allowed values for `NODE_ENV` are `production`, `development` and `test`. [Good to know](#good-to-know) ----------------------------- * If you are using a [`/src` directory](/docs/app/building-your-application/configuring/src-directory), `.env.*` files should remain in the root of your project. * If the environment variable `NODE_ENV` is unassigned, Next.js automatically assigns `development` when running the `next dev` command, or `production` for all other commands. [Version History](#version-history) ----------------------------------- Version Changes `v9.4.0` Support `.env` and `NEXT_PUBLIC_` introduced. [Previous ESLint ](/docs/app/building-your-application/configuring/eslint) [Next Absolute Imports and Module Path Aliases ](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"8902e5712ec6785222c34f6a4f70ede8\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/videos
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [ Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Using <video> and <iframe>](#using-video-and-iframe) * [<video>](#video) * [Common <video> tag attributes](#common-video-tag-attributes) * [Video best practices](#video-best-practices) * [<iframe>](#iframe) * [Common <iframe> tag attributes](#common-iframe-tag-attributes) * [Choosing a video embedding method](#choosing-a-video-embedding-method) * [Embedding externally hosted videos](#embedding-externally-hosted-videos) * [Self-hosted videos](#self-hosted-videos) * [Using Vercel Blob for video hosting](#using-vercel-blob-for-video-hosting) * [Adding subtitles to your video](#adding-subtitles-to-your-video) * [Resources](#resources) * [Open source next-video component](#open-source-next-video-component) * [Cloudinary Integration](#cloudinary-integration) * [Mux Video API](#mux-video-api) * [Fastly](#fastly) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/02-videos.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Videos Video Optimization ================== This page outlines how to use videos with Next.js applications, showing how to store and display video files without affecting performance. [Using `<video>` and `<iframe>`](#using-video-and-iframe) --------------------------------------------------------- Videos can be embedded on the page using the HTML **`<video>`** tag for direct video files and **`<iframe>`** for external platform-hosted videos. ### [`<video>`](#video) The HTML [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) tag can embed self-hosted or directly served video content, allowing full control over the playback and appearance. app/ui/video.jsx export function Video() { return ( <video width="320" height="240" controls preload="none"> <source src="/path/to/video.mp4" type="video/mp4" /> <track src="/path/to/captions.vtt" kind="subtitles" srcLang="en" label="English" /> Your browser does not support the video tag. </video> ) } ### [Common `<video>` tag attributes](#common-video-tag-attributes) Attribute Description Example Value `src` Specifies the source of the video file. `<video src="/path/to/video.mp4" />` `width` Sets the width of the video player. `<video width="320" />` `height` Sets the height of the video player. `<video height="240" />` `controls` If present, it displays the default set of playback controls. `<video controls />` `autoPlay` Automatically starts playing the video when the page loads. Note: Autoplay policies vary across browsers. `<video autoPlay />` `loop` Loops the video playback. `<video loop />` `muted` Mutes the audio by default. Often used with `autoPlay`. `<video muted />` `preload` Specifies how the video is preloaded. Values: `none`, `metadata`, `auto`. `<video preload="none" />` `playsInline` Enables inline playback on iOS devices, often necessary for autoplay to work on iOS Safari. `<video playsInline />` > **Good to know**: When using the `autoPlay` attribute, it is important to also include the `muted` attribute to ensure the video plays automatically in most browsers and the `playsInline` attribute for compatibility with iOS devices. For a comprehensive list of video attributes, refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attributes). ### [Video best practices](#video-best-practices) * **Fallback Content:** When using the `<video>` tag, include fallback content inside the tag for browsers that do not support video playback. * **Subtitles or Captions:** Include subtitles or captions for users who are deaf or hard of hearing. Utilize the [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) tag with your `<video>` elements to specify caption file sources. * **Accessible Controls:** Standard HTML5 video controls are recommended for keyboard navigation and screen reader compatibility. For advanced needs, consider third-party players like [react-player](https://github.com/cookpete/react-player) or [video.js](https://videojs.com/), which offer accessible controls and consistent browser experience. ### [`<iframe>`](#iframe) The HTML `<iframe>` tag allows you to embed videos from external platforms like YouTube or Vimeo. app/page.jsx export default function Page() { return ( <iframe src="https://www.youtube.com/watch?v=gfU1iZnjRZM" frameborder="0" allowfullscreen /> ) } ### [Common `<iframe>` tag attributes](#common-iframe-tag-attributes) Attribute Description Example Value `src` The URL of the page to embed. `<iframe src="https://example.com" />` `width` Sets the width of the iframe. `<iframe width="500" />` `height` Sets the height of the iframe. `<iframe height="300" />` `frameborder` Specifies whether or not to display a border around the iframe. `<iframe frameborder="0" />` `allowfullscreen` Allows the iframe content to be displayed in full-screen mode. `<iframe allowfullscreen />` `sandbox` Enables an extra set of restrictions on the content within the iframe. `<iframe sandbox />` `loading` Optimize loading behavior (e.g., lazy loading). `<iframe loading="lazy" />` `title` Provides a title for the iframe to support accessibility. `<iframe title="Description" />` For a comprehensive list of iframe attributes, refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attributes). ### [Choosing a video embedding method](#choosing-a-video-embedding-method) There are two ways you can embed videos in your Next.js application: * **Self-hosted or direct video files:** Embed self-hosted videos using the `<video>` tag for scenarios requiring detailed control over the player's functionality and appearance. This integration method within Next.js allows for customization and control of your video content. * **Using video hosting services (YouTube, Vimeo, etc.):** For video hosting services like YouTube or Vimeo, you'll embed their iframe-based players using the `<iframe>` tag. While this method limits some control over the player, it offers ease of use and features provided by these platforms. Choose the embedding method that aligns with your application's requirements and the user experience you aim to deliver. ### [Embedding externally hosted videos](#embedding-externally-hosted-videos) To embed videos from external platforms, you can use Next.js to fetch the video information and React Suspense to handle the fallback state while loading. **1\. Create a Server Component for video embedding** The first step is to create a [Server Component](https://nextjs.org/docs/app/building-your-application/rendering/server-components) that generates the appropriate iframe for embedding the video. This component will fetch the source URL for the video and render the iframe. app/ui/video-component.jsx export default async function VideoComponent() { const src = await getVideoSrc() return <iframe src={src} frameborder="0" allowfullscreen /> } **2\. Stream the video component using React Suspense** After creating the Server Component to embed the video, the next step is to [stream](https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming) the component using [React Suspense](https://react.dev/reference/react/Suspense). app/page.jsx import { Suspense } from 'react' import VideoComponent from '../ui/VideoComponent.jsx' export default function Page() { return ( <section> <Suspense fallback={<p>Loading video...</p>}> <VideoComponent /> </Suspense> {/* Other content of the page */} </section> ) } > **Good to know**: When embedding videos from external platforms, consider the following best practices: > > * Ensure the video embeds are responsive. Use CSS to make the iframe or video player adapt to different screen sizes. > * Implement [strategies for loading videos](https://yoast.com/site-speed-tips-for-faster-video/) based on network conditions, especially for users with limited data plans. This approach results in a better user experience as it prevents the page from blocking, meaning the user can interact with the page while the video component streams in. For a more engaging and informative loading experience, consider using a loading skeleton as the fallback UI. So instead of showing a simple loading message, you can show a skeleton that resembles the video player like this: app/page.jsx import { Suspense } from 'react' import VideoComponent from '../ui/VideoComponent.jsx' import VideoSkeleton from '../ui/VideoSkeleton.jsx' export default function Page() { return ( <section> <Suspense fallback={<VideoSkeleton />}> <VideoComponent /> </Suspense> {/* Other content of the page */} </section> ) } [Self-hosted videos](#self-hosted-videos) ----------------------------------------- Self-hosting videos may be preferable for several reasons: * **Complete control and independence**: Self-hosting gives you direct management over your video content, from playback to appearance, ensuring full ownership and control, free from external platform constraints. * **Customization for specific needs**: Ideal for unique requirements, like dynamic background videos, it allows for tailored customization to align with design and functional needs. * **Performance and scalability considerations**: Choose storage solutions that are both high-performing and scalable, to support increasing traffic and content size effectively. * **Cost and integration**: Balance the costs of storage and bandwidth with the need for easy integration into your Next.js framework and broader tech ecosystem. ### [Using Vercel Blob for video hosting](#using-vercel-blob-for-video-hosting) [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) offers an efficient way to host videos, providing a scalable cloud storage solution that works well with Next.js. Here's how you can host a video using Vercel Blob: **1\. Uploading a video to Vercel Blob** In your Vercel dashboard, navigate to the "Storage" tab and select your [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) store. In the Blob table's upper-right corner, find and click the "Upload" button. Then, choose the video file you wish to upload. After the upload completes, the video file will appear in the Blob table. Alternatively, you can upload your video using a server action. For detailed instructions, refer to the Vercel documentation on [server-side uploads](https://vercel.com/docs/storage/vercel-blob/server-upload). Vercel also supports [client-side uploads](https://vercel.com/docs/storage/vercel-blob/client-upload). This method may be preferable for certain use cases. **2\. Displaying the video in Next.js** Once the video is uploaded and stored, you can display it in your Next.js application. Here's an example of how to do this using the `<video>` tag and React Suspense: app/page.jsx import { Suspense } from 'react' import { list } from '@vercel/blob' export default function Page() { return ( <Suspense fallback={<p>Loading video...</p>}> <VideoComponent fileName="my-video.mp4" /> </Suspense> ) } async function VideoComponent({ fileName }) { const { blobs } = await list({ prefix: fileName, limit: 1, }) const { url } = blobs[0] return ( <video controls preload="none" aria-label="Video player"> <source src={url} type="video/mp4" /> Your browser does not support the video tag. </video> ) } In this approach, the page uses the video's `@vercel/blob` URL to display the video using the `VideoComponent`. React Suspense is used to show a fallback until the video URL is fetched and the video is ready to be displayed. ### [Adding subtitles to your video](#adding-subtitles-to-your-video) If you have subtitles for your video, you can easily add them using the `<track>` element inside your `<video>` tag. You can fetch the subtitle file from [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) in a similar way as the video file. Here's how you can update the `<VideoComponent>` to include subtitles. app/page.jsx async function VideoComponent({ fileName }) { const {blobs} = await list({ prefix: fileName, limit: 2 }); const { url } = blobs[0]; const { url: captionsUrl } = blobs[1]; return ( <video controls preload="none" aria-label="Video player"> <source src={url} type="video/mp4" /> <track src={captionsUrl} kind="subtitles" srcLang="en" label="English"> Your browser does not support the video tag. </video> ); }; By following this approach, you can effectively self-host and integrate videos into your Next.js applications. [Resources](#resources) ----------------------- To continue learning more about video optimization and best practices, please refer to the following resources: * **Understanding video formats and codecs**: Choose the right format and codec, like MP4 for compatibility or WebM for web optimization, for your video needs. For more details, see [Mozilla's guide on video codecs](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs). * **Video compression**: Use tools like FFmpeg to effectively compress videos, balancing quality with file size. Learn about compression techniques at [FFmpeg's official website](https://www.ffmpeg.org/). * **Resolution and bitrate adjustment**: Adjust [resolution and bitrate](https://www.dacast.com/blog/bitrate-vs-resolution/#:~:text=The%20two%20measure%20different%20aspects,yield%20different%20qualities%20of%20video) based on the viewing platform, with lower settings for mobile devices. * **Content Delivery Networks (CDNs)**: Utilize a CDN to enhance video delivery speed and manage high traffic. When using some storage solutions, such as Vercel Blob, CDN functionality is automatically handled for you. [Learn more](https://vercel.com/docs/edge-network/overview?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) about CDNs and their benefits. Explore these video streaming platforms for integrating video into your Next.js projects: ### [Open source `next-video` component](#open-source-next-video-component) * Provides a `<Video>` component for Next.js, compatible with various hosting services including [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), S3, Backblaze, and Mux. * [Detailed documentation](https://next-video.dev/docs) for using `next-video.dev` with different hosting services. ### [Cloudinary Integration](#cloudinary-integration) * Official [documentation and integration guide](https://next.cloudinary.dev/) for using Cloudinary with Next.js. * Includes a `<CldVideoPlayer>` component for [drop-in video support](https://next.cloudinary.dev/cldvideoplayer/basic-usage). * Find [examples](https://github.com/cloudinary-community/cloudinary-examples/?tab=readme-ov-file#nextjs) of integrating Cloudinary with Next.js including [Adaptive Bitrate Streaming](https://github.com/cloudinary-community/cloudinary-examples/tree/main/examples/nextjs-cldvideoplayer-abr). * Other [Cloudinary libraries](https://cloudinary.com/documentation) including a Node.js SDK are also available. ### [Mux Video API](#mux-video-api) * Mux provides a [starter template](https://github.com/muxinc/video-course-starter-kit) for creating a video course with Mux and Next.js. * Learn about Mux's recommendations for embedding [high-performance video for your Next.js application](https://www.mux.com/for/nextjs). * Explore an [example project](https://with-mux-video.vercel.app/) demonstrating Mux with Next.js. ### [Fastly](#fastly) * Learn more about integrating Fastly's solutions for [video on demand](https://www.fastly.com/products/streaming-media/video-on-demand) and streaming media into Next.js. [Previous Images ](/docs/app/building-your-application/optimizing/images) [Next Fonts ](/docs/app/building-your-application/optimizing/fonts) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"b92405f4feb2f48c9a4d2bc480d62be1\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/components/script
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [ <Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Props](#props) * [Required Props](#required-props) * [src](#src) * [Optional Props](#optional-props) * [strategy](#strategy) * [beforeInteractive](#beforeinteractive) * [afterInteractive](#afterinteractive) * [lazyOnload](#lazyonload) * [worker](#worker) * [onLoad](#onload) * [onReady](#onready) * [onError](#onerror) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/01-components/script.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Components](/docs/app/api-reference/components)<Script> <Script> ======== This API reference will help you understand how to use [props](#props) available for the Script Component. For features and usage, please see the [Optimizing Scripts](/docs/app/building-your-application/optimizing/scripts) page. app/dashboard/page.tsx TypeScript JavaScriptTypeScript import Script from 'next/script' export default function Dashboard() { return ( <> <Script src="https://example.com/script.js" /> </> ) } [Props](#props) --------------- Here's a summary of the props available for the Script Component: Prop Example Type Required [`src`](#src) `src="http://example.com/script"` String Required unless inline script is used [`strategy`](#strategy) `strategy="lazyOnload"` String \- [`onLoad`](#onload) `onLoad={onLoadFunc}` Function \- [`onReady`](#onready) `onReady={onReadyFunc}` Function \- [`onError`](#onerror) `onError={onErrorFunc}` Function \- [Required Props](#required-props) --------------------------------- The `<Script />` component requires the following properties. ### [`src`](#src) A path string specifying the URL of an external script. This can be either an absolute external URL or an internal path. The `src` property is required unless an inline script is used. [Optional Props](#optional-props) --------------------------------- The `<Script />` component accepts a number of additional properties beyond those which are required. ### [`strategy`](#strategy) The loading strategy of the script. There are four different strategies that can be used: * `beforeInteractive`: Load before any Next.js code and before any page hydration occurs. * `afterInteractive`: (**default**) Load early but after some hydration on the page occurs. * `lazyOnload`: Load during browser idle time. * `worker`: (experimental) Load in a web worker. ### [`beforeInteractive`](#beforeinteractive) Scripts that load with the `beforeInteractive` strategy are injected into the initial HTML from the server, downloaded before any Next.js module, and executed in the order they are placed before _any_ hydration occurs on the page. Scripts denoted with this strategy are preloaded and fetched before any first-party code, but their execution does not block page hydration from occurring. `beforeInteractive` scripts must be placed inside the root layout (`app/layout.tsx`) and are designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side). **This strategy should only be used for critical scripts that need to be fetched before any part of the page becomes interactive.** app/layout.tsx TypeScript JavaScriptTypeScript import Script from 'next/script' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body> {children} <Script src="https://example.com/script.js" strategy="beforeInteractive" /> </body> </html> ) } > **Good to know**: Scripts with `beforeInteractive` will always be injected inside the `head` of the HTML document regardless of where it's placed in the component. Some examples of scripts that should be loaded as soon as possible with `beforeInteractive` include: * Bot detectors * Cookie consent managers ### [`afterInteractive`](#afterinteractive) Scripts that use the `afterInteractive` strategy are injected into the HTML client-side and will load after some (or all) hydration occurs on the page. **This is the default strategy** of the Script component and should be used for any script that needs to load as soon as possible but not before any first-party Next.js code. `afterInteractive` scripts can be placed inside of any page or layout and will only load and execute when that page (or group of pages) is opened in the browser. app/page.js import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" strategy="afterInteractive" /> </> ) } Some examples of scripts that are good candidates for `afterInteractive` include: * Tag managers * Analytics ### [`lazyOnload`](#lazyonload) Scripts that use the `lazyOnload` strategy are injected into the HTML client-side during browser idle time and will load after all resources on the page have been fetched. This strategy should be used for any background or low priority scripts that do not need to load early. `lazyOnload` scripts can be placed inside of any page or layout and will only load and execute when that page (or group of pages) is opened in the browser. app/page.js import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" strategy="lazyOnload" /> </> ) } Examples of scripts that do not need to load immediately and can be fetched with `lazyOnload` include: * Chat support plugins * Social media widgets ### [`worker`](#worker) > **Warning:** The `worker` strategy is not yet stable and does not yet work with the [`app`](/docs/app/building-your-application/routing/defining-routes) directory. Use with caution. Scripts that use the `worker` strategy are off-loaded to a web worker in order to free up the main thread and ensure that only critical, first-party resources are processed on it. While this strategy can be used for any script, it is an advanced use case that is not guaranteed to support all third-party scripts. To use `worker` as a strategy, the `nextScriptWorkers` flag must be enabled in `next.config.js`: next.config.js module.exports = { experimental: { nextScriptWorkers: true, }, } `worker` scripts can **only currently be used in the `pages/` directory**: pages/home.tsx TypeScript JavaScriptTypeScript import Script from 'next/script' export default function Home() { return ( <> <Script src="https://example.com/script.js" strategy="worker" /> </> ) } ### [`onLoad`](#onload) > **Warning:** `onLoad` does not yet work with Server Components and can only be used in Client Components. Further, `onLoad` can't be used with `beforeInteractive` – consider using `onReady` instead. Some third-party scripts require users to run JavaScript code once after the script has finished loading in order to instantiate content or call a function. If you are loading a script with either afterInteractive or lazyOnload as a loading strategy, you can execute code after it has loaded using the onLoad property. Here's an example of executing a lodash method only after the library has been loaded. app/page.tsx TypeScript JavaScriptTypeScript 'use client' import Script from 'next/script' export default function Page() { return ( <> <Script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" onLoad={() => { console.log(_.sample([1, 2, 3, 4])) }} /> </> ) } ### [`onReady`](#onready) > **Warning:** `onReady` does not yet work with Server Components and can only be used in Client Components. Some third-party scripts require users to run JavaScript code after the script has finished loading and every time the component is mounted (after a route navigation for example). You can execute code after the script's load event when it first loads and then after every subsequent component re-mount using the onReady property. Here's an example of how to re-instantiate a Google Maps JS embed every time the component is mounted: app/page.tsx TypeScript JavaScriptTypeScript 'use client' import { useRef } from 'react' import Script from 'next/script' export default function Page() { const mapRef = useRef() return ( <> <div ref={mapRef}></div> <Script id="google-maps" src="https://maps.googleapis.com/maps/api/js" onReady={() => { new google.maps.Map(mapRef.current, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }) }} /> </> ) } ### [`onError`](#onerror) > **Warning:** `onError` does not yet work with Server Components and can only be used in Client Components. `onError` cannot be used with the `beforeInteractive` loading strategy. Sometimes it is helpful to catch when a script fails to load. These errors can be handled with the onError property: app/page.tsx TypeScript JavaScriptTypeScript 'use client' import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" onError={(e: Error) => { console.error('Script failed to load', e) }} /> </> ) } [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `beforeInteractive` and `afterInteractive` is modified to support `app`. `v12.2.4` `onReady` prop added. `v12.2.2` Allow `next/script` with `beforeInteractive` to be placed in `_document`. `v11.0.0` `next/script` introduced. [Previous <Link> ](/docs/app/api-reference/components/link) [Next File Conventions ](/docs/app/api-reference/file-conventions) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"07fc6642cf65ff5995331105a860d4d3\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/colocation
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [ Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Safe colocation by default](#safe-colocation-by-default) * [Project organization features](#project-organization-features) * [Private Folders](#private-folders) * [Route Groups](#route-groups) * [src Directory](#src-directory) * [Module Path Aliases](#module-path-aliases) * [Project organization strategies](#project-organization-strategies) * [Store project files outside of app](#store-project-files-outside-of-app) * [Store project files in top-level folders inside of app](#store-project-files-in-top-level-folders-inside-of-app) * [Split project files by feature or route](#split-project-files-by-feature-or-route) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/08-colocation.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Project Organization Project Organization and File Colocation ======================================== Apart from [routing folder and file conventions](/docs/getting-started/project-structure#app-routing-conventions), Next.js is **unopinionated** about how you organize and colocate your project files. This page shares default behavior and features you can use to organize your project. * [Safe colocation by default](#safe-colocation-by-default) * [Project organization features](#project-organization-features) * [Project organization strategies](#project-organization-strategies) [Safe colocation by default](#safe-colocation-by-default) --------------------------------------------------------- In the `app` directory, [nested folder hierarchy](/docs/app/building-your-application/routing#route-segments) defines route structure. Each folder represents a route segment that is mapped to a corresponding segment in a URL path. However, even though route structure is defined through folders, a route is **not publicly accessible** until a `page.js` or `route.js` file is added to a route segment. ![A diagram showing how a route is not publicly accessible until a page.js or route.js file is added to a route segment.](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-not-routable.png&w=3840&q=75)![A diagram showing how a route is not publicly accessible until a page.js or route.js file is added to a route segment.](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-not-routable.png&w=3840&q=75) And, even when a route is made publicly accessible, only the **content returned** by `page.js` or `route.js` is sent to the client. ![A diagram showing how page.js and route.js files make routes publicly accessible.](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-routable.png&w=3840&q=75)![A diagram showing how page.js and route.js files make routes publicly accessible.](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-routable.png&w=3840&q=75) This means that **project files** can be **safely colocated** inside route segments in the `app` directory without accidentally being routable. ![A diagram showing colocated project files are not routable even when a segment contains a page.js or route.js file.](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-colocation.png&w=3840&q=75)![A diagram showing colocated project files are not routable even when a segment contains a page.js or route.js file.](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-colocation.png&w=3840&q=75) > **Good to know**: > > * This is different from the `pages` directory, where any file in `pages` is considered a route. > * While you **can** colocate your project files in `app` you don't **have** to. If you prefer, you can [keep them outside the `app` directory](#store-project-files-outside-of-app). [Project organization features](#project-organization-features) --------------------------------------------------------------- Next.js provides several features to help you organize your project. ### [Private Folders](#private-folders) Private folders can be created by prefixing a folder with an underscore: `_folderName` This indicates the folder is a private implementation detail and should not be considered by the routing system, thereby **opting the folder and all its subfolders** out of routing. ![An example folder structure using private folders](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-private-folders.png&w=3840&q=75)![An example folder structure using private folders](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-private-folders.png&w=3840&q=75) Since files in the `app` directory can be [safely colocated by default](#safe-colocation-by-default), private folders are not required for colocation. However, they can be useful for: * Separating UI logic from routing logic. * Consistently organizing internal files across a project and the Next.js ecosystem. * Sorting and grouping files in code editors. * Avoiding potential naming conflicts with future Next.js file conventions. > **Good to know** > > * While not a framework convention, you might also consider marking files outside private folders as "private" using the same underscore pattern. > * You can create URL segments that start with an underscore by prefixing the folder name with `%5F` (the URL-encoded form of an underscore): `%5FfolderName`. > * If you don't use private folders, it would be helpful to know Next.js [special file conventions](/docs/getting-started/project-structure#routing-files) to prevent unexpected naming conflicts. ### [Route Groups](#route-groups) Route groups can be created by wrapping a folder in parenthesis: `(folderName)` This indicates the folder is for organizational purposes and should **not be included** in the route's URL path. ![An example folder structure using route groups](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-route-groups.png&w=3840&q=75)![An example folder structure using route groups](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-route-groups.png&w=3840&q=75) Route groups are useful for: * [Organizing routes into groups](/docs/app/building-your-application/routing/route-groups#organize-routes-without-affecting-the-url-path) e.g. by site section, intent, or team. * Enabling nested layouts in the same route segment level: * [Creating multiple nested layouts in the same segment, including multiple root layouts](/docs/app/building-your-application/routing/route-groups#creating-multiple-root-layouts) * [Adding a layout to a subset of routes in a common segment](/docs/app/building-your-application/routing/route-groups#opting-specific-segments-into-a-layout) ### [`src` Directory](#src-directory) Next.js supports storing application code (including `app`) inside an optional [`src` directory](/docs/app/building-your-application/configuring/src-directory). This separates application code from project configuration files which mostly live in the root of a project. ![An example folder structure with the `src` directory](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-src-directory.png&w=3840&q=75)![An example folder structure with the `src` directory](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-src-directory.png&w=3840&q=75) ### [Module Path Aliases](#module-path-aliases) Next.js supports [Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) which make it easier to read and maintain imports across deeply nested project files. app/dashboard/settings/analytics/page.js // before import { Button } from '../../../components/button' // after import { Button } from '@/components/button' [Project organization strategies](#project-organization-strategies) ------------------------------------------------------------------- There is no "right" or "wrong" way when it comes to organizing your own files and folders in a Next.js project. The following section lists a very high-level overview of common strategies. The simplest takeaway is to choose a strategy that works for you and your team and be consistent across the project. > **Good to know**: In our examples below, we're using `components` and `lib` folders as generalized placeholders, their naming has no special framework significance and your projects might use other folders like `ui`, `utils`, `hooks`, `styles`, etc. ### [Store project files outside of `app`](#store-project-files-outside-of-app) This strategy stores all application code in shared folders in the **root of your project** and keeps the `app` directory purely for routing purposes. ![An example folder structure with project files outside of app](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-project-root.png&w=3840&q=75)![An example folder structure with project files outside of app](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-project-root.png&w=3840&q=75) ### [Store project files in top-level folders inside of `app`](#store-project-files-in-top-level-folders-inside-of-app) This strategy stores all application code in shared folders in the **root of the `app` directory**. ![An example folder structure with project files inside app](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-app-root.png&w=3840&q=75)![An example folder structure with project files inside app](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-app-root.png&w=3840&q=75) ### [Split project files by feature or route](#split-project-files-by-feature-or-route) This strategy stores globally shared application code in the root `app` directory and **splits** more specific application code into the route segments that use them. ![An example folder structure with project files split by feature or route](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-app-root-split.png&w=3840&q=75)![An example folder structure with project files split by feature or route](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-app-root-split.png&w=3840&q=75) Next Steps ---------- [ App Router ... Routing ### Defining Routes Learn how to create your first route in Next.js. ](/docs/app/building-your-application/routing/defining-routes)[ App Router ... Routing ### Route Groups Route Groups can be used to partition your Next.js application into different sections. ](/docs/app/building-your-application/routing/route-groups)[ App Router ... Configuring ### src Directory Save pages under the \`src\` directory as an alternative to the root \`pages\` directory. ](/docs/app/building-your-application/configuring/src-directory)[ App Router ... Configuring ### Absolute Imports and Module Path Aliases Configure module path aliases that allow you to remap certain import paths. ](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) [Previous Route Groups ](/docs/app/building-your-application/routing/route-groups) [Next Dynamic Routes ](/docs/app/building-your-application/routing/dynamic-routes) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"dd92cc88bdd1f0b93c8c3d1529890709\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[API Reference](/docs/app/api-reference)File Conventions File Conventions ================ [ ### default.js API Reference for the default.js file. ](/docs/app/api-reference/file-conventions/default)[ ### error.js API reference for the error.js special file. ](/docs/app/api-reference/file-conventions/error)[ ### instrumentation.js API reference for the instrumentation.js file. ](/docs/app/api-reference/file-conventions/instrumentation)[ ### layout.js API reference for the layout.js file. ](/docs/app/api-reference/file-conventions/layout)[ ### loading.js API reference for the loading.js file. ](/docs/app/api-reference/file-conventions/loading)[ ### middleware.js API reference for the middleware.js file. ](/docs/app/api-reference/file-conventions/middleware)[ ### not-found.js API reference for the not-found.js file. ](/docs/app/api-reference/file-conventions/not-found)[ ### page.js API reference for the page.js file. ](/docs/app/api-reference/file-conventions/page)[ ### route.js API reference for the route.js special file. ](/docs/app/api-reference/file-conventions/route)[ ### Route Segment Config Learn about how to configure options for Next.js route segments. ](/docs/app/api-reference/file-conventions/route-segment-config)[ ### template.js API Reference for the template.js file. ](/docs/app/api-reference/file-conventions/template)[ ### Metadata Files API documentation for the metadata file conventions. ](/docs/app/api-reference/file-conventions/metadata) [Previous <Script> ](/docs/app/api-reference/components/script) [Next default.js ](/docs/app/api-reference/file-conventions/default) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"db0dd7419ce475f596297fe724f27cf2\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/permanentRedirect
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [ permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Parameters](#parameters) * [Returns](#returns) * [Example](#example) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/permanentRedirect.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)permanentRedirect permanentRedirect ================= The `permanentRedirect` function allows you to redirect the user to another URL. `permanentRedirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). When used in a streaming context, this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 308 (Permanent) HTTP redirect response to the caller. If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api-reference/functions/not-found) instead. > **Good to know**: If you prefer to return a 307 (Temporary) HTTP redirect instead of 308 (Permanent), you can use the [`redirect` function](/docs/app/api-reference/functions/redirect) instead. [Parameters](#parameters) ------------------------- The `permanentRedirect` function accepts two arguments: permanentRedirect(path, type) Parameter Type Description `path` `string` The URL to redirect to. Can be a relative or absolute path. `type` `'replace'` (default) or `'push'` (default in Server Actions) The type of redirect to perform. By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. The `type` parameter has no effect when used in Server Components. [Returns](#returns) ------------------- `permanentRedirect` does not return any value. [Example](#example) ------------------- Invoking the `permanentRedirect()` function throws a `NEXT_REDIRECT` error and terminates rendering of the route segment in which it was thrown. app/team/\[id\]/page.js import { permanentRedirect } from 'next/navigation' async function fetchTeam(id) { const res = await fetch('https://...') if (!res.ok) return undefined return res.json() } export default async function Profile({ params }) { const team = await fetchTeam(params.id) if (!team) { permanentRedirect('/login') } // ... } > **Good to know**: `permanentRedirect` does not require you to use `return permanentRedirect()` as it uses the TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) type. Next Steps ---------- [ App Router ... Functions ### redirect API Reference for the redirect function. ](/docs/app/api-reference/functions/redirect) [Previous notFound ](/docs/app/api-reference/functions/not-found) [Next redirect ](/docs/app/api-reference/functions/redirect) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"ba5f6d5183d76bf21f1f2d670172d926\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [ Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Convention](#convention) * [Example](#example) * [Generating Static Params](#generating-static-params) * [Catch-all Segments](#catch-all-segments) * [Optional Catch-all Segments](#optional-catch-all-segments) * [TypeScript](#typescript) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/09-dynamic-routes.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Dynamic Routes Dynamic Routes ============== When you don't know the exact segment names ahead of time and want to create routes from dynamic data, you can use Dynamic Segments that are filled in at request time or [prerendered](#generating-static-params) at build time. [Convention](#convention) ------------------------- A Dynamic Segment can be created by wrapping a folder's name in square brackets: `[folderName]`. For example, `[id]` or `[slug]`. Dynamic Segments are passed as the `params` prop to [`layout`](/docs/app/api-reference/file-conventions/layout), [`page`](/docs/app/api-reference/file-conventions/page), [`route`](/docs/app/building-your-application/routing/route-handlers), and [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) functions. [Example](#example) ------------------- For example, a blog could include the following route `app/blog/[slug]/page.js` where `[slug]` is the Dynamic Segment for blog posts. app/blog/\[slug\]/page.tsx TypeScript JavaScriptTypeScript export default function Page({ params }: { params: { slug: string } }) { return <div>My Post: {params.slug}</div> } Route Example URL `params` `app/blog/[slug]/page.js` `/blog/a` `{ slug: 'a' }` `app/blog/[slug]/page.js` `/blog/b` `{ slug: 'b' }` `app/blog/[slug]/page.js` `/blog/c` `{ slug: 'c' }` See the [generateStaticParams()](#generating-static-params) page to learn how to generate the params for the segment. > **Good to know**: Dynamic Segments are equivalent to [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) in the `pages` directory. [Generating Static Params](#generating-static-params) ----------------------------------------------------- The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/building-your-application/routing/dynamic-routes) to [**statically generate**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) routes at build time instead of on-demand at request time. app/blog/\[slug\]/page.tsx TypeScript JavaScriptTypeScript export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } The primary benefit of the `generateStaticParams` function is its smart retrieval of data. If content is fetched within the `generateStaticParams` function using a `fetch` request, the requests are [automatically memoized](/docs/app/building-your-application/caching#request-memoization). This means a `fetch` request with the same arguments across multiple `generateStaticParams`, Layouts, and Pages will only be made once, which decreases build times. Use the [migration guide](/docs/app/building-your-application/upgrading/app-router-migration#dynamic-paths-getstaticpaths) if you are migrating from the `pages` directory. See [`generateStaticParams` server function documentation](/docs/app/api-reference/functions/generate-static-params) for more information and advanced use cases. [Catch-all Segments](#catch-all-segments) ----------------------------------------- Dynamic Segments can be extended to **catch-all** subsequent segments by adding an ellipsis inside the brackets `[...folderName]`. For example, `app/shop/[...slug]/page.js` will match `/shop/clothes`, but also `/shop/clothes/tops`, `/shop/clothes/tops/t-shirts`, and so on. Route Example URL `params` `app/shop/[...slug]/page.js` `/shop/a` `{ slug: ['a'] }` `app/shop/[...slug]/page.js` `/shop/a/b` `{ slug: ['a', 'b'] }` `app/shop/[...slug]/page.js` `/shop/a/b/c` `{ slug: ['a', 'b', 'c'] }` [Optional Catch-all Segments](#optional-catch-all-segments) ----------------------------------------------------------- Catch-all Segments can be made **optional** by including the parameter in double square brackets: `[[...folderName]]`. For example, `app/shop/[[...slug]]/page.js` will **also** match `/shop`, in addition to `/shop/clothes`, `/shop/clothes/tops`, `/shop/clothes/tops/t-shirts`. The difference between **catch-all** and **optional catch-all** segments is that with optional, the route without the parameter is also matched (`/shop` in the example above). Route Example URL `params` `app/shop/[[...slug]]/page.js` `/shop` `{}` `app/shop/[[...slug]]/page.js` `/shop/a` `{ slug: ['a'] }` `app/shop/[[...slug]]/page.js` `/shop/a/b` `{ slug: ['a', 'b'] }` `app/shop/[[...slug]]/page.js` `/shop/a/b/c` `{ slug: ['a', 'b', 'c'] }` [TypeScript](#typescript) ------------------------- When using TypeScript, you can add types for `params` depending on your configured route segment. app/blog/\[slug\]/page.tsx TypeScript JavaScriptTypeScript export default function Page({ params }: { params: { slug: string } }) { return <h1>My Page</h1> } Route `params` Type Definition `app/blog/[slug]/page.js` `{ slug: string }` `app/shop/[...slug]/page.js` `{ slug: string[] }` `app/shop/[[...slug]]/page.js` `{ slug?: string[] }` `app/[categoryId]/[itemId]/page.js` `{ categoryId: string, itemId: string }` > **Good to know**: This may be done automatically by the [TypeScript plugin](/docs/app/building-your-application/configuring/typescript#typescript-plugin) in the future. Next Steps ---------- For more information on what to do next, we recommend the following sections [ App Router ... Routing ### Linking and Navigating Learn how navigation works in Next.js, and how to use the Link Component and \`useRouter\` hook. ](/docs/app/building-your-application/routing/linking-and-navigating)[ App Router ... Functions ### generateStaticParams API reference for the generateStaticParams function. ](/docs/app/api-reference/functions/generate-static-params) [Previous Project Organization ](/docs/app/building-your-application/routing/colocation) [Next Parallel Routes ](/docs/app/building-your-application/routing/parallel-routes) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"b15b999100562437ec07fbf000b28867\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/mdx
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [ MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [@next/mdx](#nextmdx) * [Getting Started](#getting-started) * [Remote MDX](#remote-mdx) * [Layouts](#layouts) * [Remark and Rehype Plugins](#remark-and-rehype-plugins) * [Frontmatter](#frontmatter) * [Custom Elements](#custom-elements) * [Deep Dive: How do you transform markdown into HTML?](#deep-dive-how-do-you-transform-markdown-into-html) * [Using the Rust-based MDX compiler (Experimental)](#using-the-rust-based-mdx-compiler-experimental) * [Helpful Links](#helpful-links) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/05-mdx.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)MDX Markdown and MDX ================ [Markdown](https://daringfireball.net/projects/markdown/syntax) is a lightweight markup language used to format text. It allows you to write using plain text syntax and convert it to structurally valid HTML. It's commonly used for writing content on websites and blogs. You write... I **love** using [Next.js](https://nextjs.org/) Output: <p>I <strong>love</strong> using <a href="https://nextjs.org/">Next.js</a></p> [MDX](https://mdxjs.com/) is a superset of markdown that lets you write [JSX](https://react.dev/learn/writing-markup-with-jsx) directly in your markdown files. It is a powerful way to add dynamic interactivity and embed React components within your content. Next.js can support both local MDX content inside your application, as well as remote MDX files fetched dynamically on the server. The Next.js plugin handles transforming markdown and React components into HTML, including support for usage in Server Components (the default in App Router). [`@next/mdx`](#nextmdx) ----------------------- The `@next/mdx` package is used to configure Next.js so it can process markdown and MDX. **It sources data from local files**, allowing you to create pages with a `.mdx` extension, directly in your `/pages` or `/app` directory. Let's walk through how to configure and use MDX with Next.js. [Getting Started](#getting-started) ----------------------------------- Install packages needed to render MDX: Terminal npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx Create a `mdx-components.tsx` file at the root of your application (`src/` or the parent folder of `app/`): > **Good to know**: `mdx-components.tsx` is required to use MDX with App Router and will not work without it. mdx-components.tsx TypeScript JavaScriptTypeScript import type { MDXComponents } from 'mdx/types' export function useMDXComponents(components: MDXComponents): MDXComponents { return { ...components, } } Update the `next.config.js` file at your project's root to configure it to use MDX: next.config.js const withMDX = require('@next/mdx')() /** @type {import('next').NextConfig} */ const nextConfig = { // Configure `pageExtensions` to include MDX files pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'], // Optionally, add any other Next.js config below } module.exports = withMDX(nextConfig) Then, create a new MDX page within the `/app` directory: your-project ├── app │ └── my-mdx-page │ └── page.mdx └── package.json Now you can use markdown and import React components directly inside your MDX page: import { MyComponent } from 'my-components' # Welcome to my MDX page! This is some **bold** and _italics_ text. This is a list in markdown: - One - Two - Three Checkout my React component: <MyComponent /> Navigating to the `/my-mdx-page` route should display your rendered MDX. [Remote MDX](#remote-mdx) ------------------------- If your markdown or MDX files or content lives _somewhere else_, you can fetch it dynamically on the server. This is useful for content stored in a separate local folder, CMS, database, or anywhere else. A popular community package for this use is [`next-mdx-remote`](https://github.com/hashicorp/next-mdx-remote#react-server-components-rsc--nextjs-app-directory-support). > **Good to know**: Please proceed with caution. MDX compiles to JavaScript and is executed on the server. You should only fetch MDX content from a trusted source, otherwise this can lead to remote code execution (RCE). The following example uses `next-mdx-remote`: app/my-mdx-page-remote/page.tsx TypeScript JavaScriptTypeScript import { MDXRemote } from 'next-mdx-remote/rsc' export default async function RemoteMdxPage() { // MDX text - can be from a local file, database, CMS, fetch, anywhere... const res = await fetch('https://...') const markdown = await res.text() return <MDXRemote source={markdown} /> } Navigating to the `/my-mdx-page-remote` route should display your rendered MDX. [Layouts](#layouts) ------------------- To share a layout across MDX pages, you can use the [built-in layouts support](/docs/app/building-your-application/routing/pages-and-layouts#layouts) with the App Router. app/my-mdx-page/layout.tsx TypeScript JavaScriptTypeScript export default function MdxLayout({ children }: { children: React.ReactNode }) { // Create any shared layout or styles here return <div style={{ color: 'blue' }}>{children}</div> } [Remark and Rehype Plugins](#remark-and-rehype-plugins) ------------------------------------------------------- You can optionally provide `remark` and `rehype` plugins to transform the MDX content. For example, you can use `remark-gfm` to support GitHub Flavored Markdown. Since the `remark` and `rehype` ecosystem is ESM only, you'll need to use `next.config.mjs` as the configuration file. next.config.mjs import remarkGfm from 'remark-gfm' import createMDX from '@next/mdx' /** @type {import('next').NextConfig} */ const nextConfig = { // Configure `pageExtensions`` to include MDX files pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'], // Optionally, add any other Next.js config below } const withMDX = createMDX({ // Add markdown plugins here, as desired options: { remarkPlugins: [remarkGfm], rehypePlugins: [], }, }) // Wrap MDX and Next.js config with each other export default withMDX(nextConfig) [Frontmatter](#frontmatter) --------------------------- Frontmatter is a YAML like key/value pairing that can be used to store data about a page. `@next/mdx` does **not** support frontmatter by default, though there are many solutions for adding frontmatter to your MDX content, such as: * [remark-frontmatter](https://github.com/remarkjs/remark-frontmatter) * [remark-mdx-frontmatter](https://github.com/remcohaszing/remark-mdx-frontmatter) * [gray-matter](https://github.com/jonschlinkert/gray-matter). To access page metadata with `@next/mdx`, you can export a metadata object from within the `.mdx` file: export const metadata = { author: 'John Doe', } # My MDX page [Custom Elements](#custom-elements) ----------------------------------- One of the pleasant aspects of using markdown, is that it maps to native `HTML` elements, making writing fast, and intuitive: This is a list in markdown: - One - Two - Three The above generates the following `HTML`: <p>This is a list in markdown:</p> <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> When you want to style your own elements for a custom feel to your website or application, you can pass in shortcodes. These are your own custom components that map to `HTML` elements. To do this, open the `mdx-components.tsx` file at the root of your application and add custom elements: mdx-components.tsx TypeScript JavaScriptTypeScript import type { MDXComponents } from 'mdx/types' import Image, { ImageProps } from 'next/image' // This file allows you to provide custom React components // to be used in MDX files. You can import and use any // React component you want, including inline styles, // components from other libraries, and more. export function useMDXComponents(components: MDXComponents): MDXComponents { return { // Allows customizing built-in components, e.g. to add styling. h1: ({ children }) => <h1 style={{ fontSize: '100px' }}>{children}</h1>, img: (props) => ( <Image sizes="100vw" style={{ width: '100%', height: 'auto' }} {...(props as ImageProps)} /> ), ...components, } } [Deep Dive: How do you transform markdown into HTML?](#deep-dive-how-do-you-transform-markdown-into-html) --------------------------------------------------------------------------------------------------------- React does not natively understand markdown. The markdown plaintext needs to first be transformed into HTML. This can be accomplished with `remark` and `rehype`. `remark` is an ecosystem of tools around markdown. `rehype` is the same, but for HTML. For example, the following code snippet transforms markdown into HTML: import { unified } from 'unified' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' main() async function main() { const file = await unified() .use(remarkParse) // Convert into markdown AST .use(remarkRehype) // Transform to HTML AST .use(rehypeSanitize) // Sanitize HTML input .use(rehypeStringify) // Convert AST into serialized HTML .process('Hello, Next.js!') console.log(String(file)) // <p>Hello, Next.js!</p> } The `remark` and `rehype` ecosystem contains plugins for [syntax highlighting](https://github.com/atomiks/rehype-pretty-code), [linking headings](https://github.com/rehypejs/rehype-autolink-headings), [generating a table of contents](https://github.com/remarkjs/remark-toc), and more. When using `@next/mdx` as shown above, you **do not** need to use `remark` or `rehype` directly, as it is handled for you. We're describing it here for a deeper understanding of what the `@next/mdx` package is doing underneath. [Using the Rust-based MDX compiler (Experimental)](#using-the-rust-based-mdx-compiler-experimental) --------------------------------------------------------------------------------------------------- Next.js supports a new MDX compiler written in Rust. This compiler is still experimental and is not recommended for production use. To use the new compiler, you need to configure `next.config.js` when you pass it to `withMDX`: next.config.js module.exports = withMDX({ experimental: { mdxRs: true, }, }) [Helpful Links](#helpful-links) ------------------------------- * [MDX](https://mdxjs.com) * [`@next/mdx`](https://www.npmjs.com/package/@next/mdx) * [remark](https://github.com/remarkjs/remark) * [rehype](https://github.com/rehypejs/rehype) * [Markdoc](https://markdoc.dev/docs/nextjs) [Previous Absolute Imports and Module Path Aliases ](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) [Next src Directory ](/docs/app/building-your-application/configuring/src-directory) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"2f84d4ab1289d99aedf648369947a1ec\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [ Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Google Fonts](#google-fonts) * [Specifying a subset](#specifying-a-subset) * [Using Multiple Fonts](#using-multiple-fonts) * [Local Fonts](#local-fonts) * [With Tailwind CSS](#with-tailwind-css) * [Preloading](#preloading) * [Reusing fonts](#reusing-fonts) * [API Reference](#api-reference) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/03-fonts.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Fonts Font Optimization ================= [**`next/font`**](/docs/app/api-reference/components/font) will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance. > **🎥 Watch:** Learn more about using `next/font` → [YouTube (6 minutes)](https://www.youtube.com/watch?v=L8_98i_bMMA). `next/font` includes **built-in automatic self-hosting** for _any_ font file. This means you can optimally load web fonts with zero layout shift, thanks to the underlying CSS `size-adjust` property used. This new font system also allows you to conveniently use all Google Fonts with performance and privacy in mind. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. **No requests are sent to Google by the browser.** [Google Fonts](#google-fonts) ----------------------------- Automatically self-host any Google Font. Fonts are included in the deployment and served from the same domain as your deployment. **No requests are sent to Google by the browser.** Get started by importing the font you would like to use from `next/font/google` as a function. We recommend using [variable fonts](https://fonts.google.com/variablefonts) for the best performance and flexibility. app/layout.tsx TypeScript JavaScriptTypeScript 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 function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={inter.className}> <body>{children}</body> </html> ) } If you can't use a variable font, you will **need to specify a weight**: app/layout.tsx TypeScript JavaScriptTypeScript import { Roboto } from 'next/font/google' const roboto = Roboto({ weight: '400', subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={roboto.className}> <body>{children}</body> </html> ) } You can specify multiple weights and/or styles by using an array: app/layout.js const roboto = Roboto({ weight: ['400', '700'], style: ['normal', 'italic'], subsets: ['latin'], display: 'swap', }) > **Good to know**: Use an underscore (\_) for font names with multiple words. E.g. `Roboto Mono` should be imported as `Roboto_Mono`. ### [Specifying a subset](#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 subsets you want to preload. Failing to specify any subsets while [`preload`](/docs/app/api-reference/components/font#preload) is `true` will result in a warning. This can be done by adding it to the function call: app/layout.tsx TypeScript JavaScriptTypeScript const inter = Inter({ subsets: ['latin'] }) View the [Font API Reference](/docs/app/api-reference/components/font) for more information. ### [Using Multiple Fonts](#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 `className` where needed. This ensures the font is preloaded only when it's rendered: app/fonts.ts TypeScript JavaScriptTypeScript import { Inter, Roboto_Mono } from 'next/font/google' export const inter = Inter({ subsets: ['latin'], display: 'swap', }) export const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', }) app/layout.tsx TypeScript JavaScriptTypeScript import { inter } from './fonts' export default function Layout({ children }: { children: React.ReactNode }) { return ( <html lang="en" className={inter.className}> <body> <div>{children}</div> </body> </html> ) } app/page.tsx TypeScript JavaScriptTypeScript import { roboto_mono } from './fonts' export default function Page() { return ( <> <h1 className={roboto_mono.className}>My page</h1> </> ) } In the example above, `Inter` will be applied globally, and `Roboto Mono` can be imported and applied as needed. Alternatively, you can create a [CSS variable](/docs/app/api-reference/components/font#variable) and use it with your preferred CSS solution: app/layout.tsx TypeScript JavaScriptTypeScript import { Inter, Roboto_Mono } from 'next/font/google' import styles from './global.css' const inter = Inter({ subsets: ['latin'], variable: '--font-inter', display: 'swap', }) const roboto_mono = Roboto_Mono({ subsets: ['latin'], variable: '--font-roboto-mono', display: 'swap', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body> <h1>My App</h1> <div>{children}</div> </body> </html> ) } app/global.css html { font-family: var(--font-inter); } h1 { font-family: var(--font-roboto-mono); } In the example above, `Inter` will be applied globally, and any `<h1>` tags will be styled with `Roboto Mono`. > **Recommendation**: Use multiple fonts conservatively since each new font is an additional resource the client has to download. [Local Fonts](#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. app/layout.tsx TypeScript JavaScriptTypeScript 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 RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={myFont.className}> <body>{children}</body> </html> ) } If you want to use multiple files for a single font family, `src` can be an array: const roboto = localFont({ src: [ { path: './Roboto-Regular.woff2', weight: '400', style: 'normal', }, { path: './Roboto-Italic.woff2', weight: '400', style: 'italic', }, { path: './Roboto-Bold.woff2', weight: '700', style: 'normal', }, { path: './Roboto-BoldItalic.woff2', weight: '700', style: 'italic', }, ], }) View the [Font API Reference](/docs/app/api-reference/components/font) for more information. [With Tailwind CSS](#with-tailwind-css) --------------------------------------- `next/font` can be used with [Tailwind CSS](https://tailwindcss.com/) through a [CSS variable](/docs/app/api-reference/components/font#css-variables). In the example below, we use the font `Inter` from `next/font/google` (you can use any font from Google or Local Fonts). Load your font with the `variable` option to define your CSS variable name and assign it to `inter`. Then, use `inter.variable` to add the CSS variable to your HTML document. app/layout.tsx TypeScript JavaScriptTypeScript import { Inter, Roboto_Mono } from 'next/font/google' const inter = Inter({ subsets: ['latin'], display: 'swap', variable: '--font-inter', }) const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', variable: '--font-roboto-mono', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body>{children}</body> </html> ) } Finally, add the CSS variable to your [Tailwind CSS config](/docs/app/building-your-application/styling/tailwind-css#configuring-tailwind): tailwind.config.js /** @type {import('tailwindcss').Config} */ module.exports = { content: [ './pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}', './app/**/*.{js,ts,jsx,tsx}', ], theme: { extend: { fontFamily: { sans: ['var(--font-inter)'], mono: ['var(--font-roboto-mono)'], }, }, }, plugins: [], } You can now use the `font-sans` and `font-mono` utility classes to apply the font to your elements. [Preloading](#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 where it is used: * If it's a [unique page](/docs/app/building-your-application/routing/pages-and-layouts#pages), it is preloaded on the unique route for that page. * If it's a [layout](/docs/app/building-your-application/routing/pages-and-layouts#layouts), it is preloaded on all the routes wrapped by the layout. * If it's the [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required), it is preloaded on all routes. [Reusing fonts](#reusing-fonts) ------------------------------- Every time you call the `localFont` or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted. In this situation, it is recommended to do the following: * Call the font loader function in one shared file * Export it as a constant * Import the constant in each file where you would like to use this font API Reference ------------- Learn more about the next/font API. [ App Router ... Components ### Font Optimizing loading web fonts with the built-in \`next/font\` loaders. ](/docs/app/api-reference/components/font) [Previous Videos ](/docs/app/building-your-application/optimizing/videos) [Next Metadata ](/docs/app/building-your-application/optimizing/metadata) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"e143e9a72c65200d3a215132d86a379a\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [ Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Absolute Imports](#absolute-imports) * [Module Aliases](#module-aliases) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/04-absolute-imports-and-module-aliases.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)Absolute Imports and Module Path Aliases Absolute Imports and Module Path Aliases ======================================== Examples * [Absolute Imports and Aliases](https://github.com/vercel/next.js/tree/canary/examples/with-absolute-imports) Next.js has in-built support for the `"paths"` and `"baseUrl"` options of `tsconfig.json` and `jsconfig.json` files. These options allow you to alias project directories to absolute paths, making it easier to import modules. For example: // before import { Button } from '../../../components/button' // after import { Button } from '@/components/button' > **Good to know**: `create-next-app` will prompt to configure these options for you. [Absolute Imports](#absolute-imports) ------------------------------------- The `baseUrl` configuration option allows you to import directly from the root of the project. An example of this configuration: tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": "." } } components/button.tsx TypeScript JavaScriptTypeScript export default function Button() { return <button>Click me</button> } app/page.tsx TypeScript JavaScriptTypeScript import Button from 'components/button' export default function HomePage() { return ( <> <h1>Hello World</h1> <Button /> </> ) } [Module Aliases](#module-aliases) --------------------------------- In addition to configuring the `baseUrl` path, you can use the `"paths"` option to "alias" module paths. For example, the following configuration maps `@/components/*` to `components/*`: tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": ".", "paths": { "@/components/*": ["components/*"] } } } components/button.tsx TypeScript JavaScriptTypeScript export default function Button() { return <button>Click me</button> } app/page.tsx TypeScript JavaScriptTypeScript import Button from '@/components/button' export default function HomePage() { return ( <> <h1>Hello World</h1> <Button /> </> ) } Each of the `"paths"` are relative to the `baseUrl` location. For example: // tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": "src/", "paths": { "@/styles/*": ["styles/*"], "@/components/*": ["components/*"] } } } // pages/index.js import Button from '@/components/button' import '@/styles/styles.css' import Helper from 'utils/helper' export default function HomePage() { return ( <Helper> <h1>Hello World</h1> <Button /> </Helper> ) } [Previous Environment Variables ](/docs/app/building-your-application/configuring/environment-variables) [Next MDX ](/docs/app/building-your-application/configuring/mdx) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"3f52d993871b488b18856716de144ffe\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions/default
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [ default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Props](#props) * [params (optional)](#params-optional) * [Learn more about Parallel Routes](#learn-more-about-parallel-routes) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/default.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[File Conventions](/docs/app/api-reference/file-conventions)default.js default.js ========== The `default.js` file is used to render a fallback within [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) when Next.js cannot recover a [slot's](/docs/app/building-your-application/routing/parallel-routes#slots) active state after a full-page load. During [soft navigation](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation), Next.js keeps track of the active _state_ (subpage) for each slot. However, for hard navigations (full-page load), Next.js cannot recover the active state. In this case, a `default.js` file can be rendered for subpages that don't match the current URL. Consider the following folder structure. The `@team` slot has a `settings` page, but `@analytics` does not. ![Parallel Routes unmatched routes](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes-unmatched-routes.png&w=3840&q=75)![Parallel Routes unmatched routes](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes-unmatched-routes.png&w=3840&q=75) When navigating to `/settings`, the `@team` slot will render the `settings` page while maintaining the currently active page for the `@analytics` slot. On refresh, Next.js will render a `default.js` for `@analytics`. If `default.js` doesn't exist, a `404` is rendered instead. Additionally, since `children` is an implicit slot, you also need to create a `default.js` file to render a fallback for `children` when Next.js cannot recover the active state of the parent page. [Props](#props) --------------- ### [`params` (optional)](#params-optional) An object containing the [dynamic route parameters](/docs/app/building-your-application/routing/dynamic-routes) from the root segment down to the slot's subpages. For example: Example URL `params` `app/@sidebar/[artist]/default.js` `/zack` `{ artist: 'zack' }` `app/@sidebar/[artist]/[album]/default.js` `/zack/next` `{ artist: 'zack', album: 'next' }` Learn more about Parallel Routes -------------------------------- [ App Router ... Routing ### Parallel Routes Simultaneously render one or more pages in the same view that can be navigated independently. A pattern for highly dynamic applications. ](/docs/app/building-your-application/routing/parallel-routes) [Previous File Conventions ](/docs/app/api-reference/file-conventions) [Next error.js ](/docs/app/api-reference/file-conventions/error) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"6aa03f21b09826098c94285ab66f5a59\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/parallel-routes
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [ Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Slots](#slots) * [Active state and navigation](#active-state-and-navigation) * [default.js](#defaultjs) * [useSelectedLayoutSegment(s)](#useselectedlayoutsegments) * [Examples](#examples) * [Conditional Routes](#conditional-routes) * [Tab Groups](#tab-groups) * [Modals](#modals) * [Opening the modal](#opening-the-modal) * [Closing the modal](#closing-the-modal) * [Loading and Error UI](#loading-and-error-ui) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/10-parallel-routes.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Parallel Routes Parallel Routes =============== Parallel Routes allows you to simultaneously or conditionally render one or more pages within the same layout. They are useful for highly dynamic sections of an app, such as dashboards and feeds on social sites. For example, considering a dashboard, you can use parallel routes to simultaneously render the `team` and `analytics` pages: ![Parallel Routes Diagram](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes.png&w=3840&q=75)![Parallel Routes Diagram](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes.png&w=3840&q=75) [Slots](#slots) --------------- Parallel routes are created using named **slots**. Slots are defined with the `@folder` convention. For example, the following file structure defines two slots: `@analytics` and `@team`: ![Parallel Routes File-system Structure](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes-file-system.png&w=3840&q=75)![Parallel Routes File-system Structure](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes-file-system.png&w=3840&q=75) Slots are passed as props to the shared parent layout. For the example above, the component in `app/layout.js` now accepts the `@analytics` and `@team` slots props, and can render them in parallel alongside the `children` prop: app/layout.tsx TypeScript JavaScriptTypeScript export default function Layout({ children, team, analytics, }: { children: React.ReactNode analytics: React.ReactNode team: React.ReactNode }) { return ( <> {children} {team} {analytics} </> ) } However, slots are **not** [route segments](/docs/app/building-your-application/routing#route-segments) and do not affect the URL structure. For example, for `/@analytics/views`, the URL will be `/views` since `@analytics` is a slot. > **Good to know**: > > * The `children` prop is an implicit slot that does not need to be mapped to a folder. This means `app/page.js` is equivalent to `app/@children/page.js`. [Active state and navigation](#active-state-and-navigation) ----------------------------------------------------------- By default, Next.js keeps track of the active _state_ (or subpage) for each slot. However, the content rendered within a slot will depend on the type of navigation: * [**Soft Navigation**](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation): During client-side navigation, Next.js will perform a [partial render](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), changing the subpage within the slot, while maintaining the other slot's active subpages, even if they don't match the current URL. * **Hard Navigation**: After a full-page load (browser refresh), Next.js cannot determine the active state for the slots that don't match the current URL. Instead, it will render a [`default.js`](#defaultjs) file for the unmatched slots, or `404` if `default.js` doesn't exist. > **Good to know**: > > * The `404` for unmatched routes helps ensure that you don't accidentally render a parallel route on a page that it was not intended for. ### [`default.js`](#defaultjs) You can define a `default.js` file to render as a fallback for unmatched slots during the initial load or full-page reload. Consider the following folder structure. The `@team` slot has a `/settings` page, but `@analytics` does not. ![Parallel Routes unmatched routes](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes-unmatched-routes.png&w=3840&q=75)![Parallel Routes unmatched routes](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes-unmatched-routes.png&w=3840&q=75) When navigating to `/settings`, the `@team` slot will render the `/settings` page while maintaining the currently active page for the `@analytics` slot. On refresh, Next.js will render a `default.js` for `@analytics`. If `default.js` doesn't exist, a `404` is rendered instead. Additionally, since `children` is an implicit slot, you also need to create a `default.js` file to render a fallback for `children` when Next.js cannot recover the active state of the parent page. ### [`useSelectedLayoutSegment(s)`](#useselectedlayoutsegments) Both [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) and [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) accept a `parallelRoutesKey` parameter, which allows you to read the active route segment within a slot. app/layout.tsx TypeScript JavaScriptTypeScript 'use client' import { useSelectedLayoutSegment } from 'next/navigation' export default function Layout({ auth }: { auth: React.ReactNode }) { const loginSegment = useSelectedLayoutSegment('auth') // ... } When a user navigates to `app/@auth/login` (or `/login` in the URL bar), `loginSegment` will be equal to the string `"login"`. [Examples](#examples) --------------------- ### [Conditional Routes](#conditional-routes) You can use Parallel Routes to conditionally render routes based on certain conditions, such as user role. For example, to render a different dashboard page for the `/admin` or `/user` roles: ![Conditional routes diagram](/_next/image?url=%2Fdocs%2Flight%2Fconditional-routes-ui.png&w=3840&q=75)![Conditional routes diagram](/_next/image?url=%2Fdocs%2Fdark%2Fconditional-routes-ui.png&w=3840&q=75) app/dashboard/layout.tsx TypeScript JavaScriptTypeScript import { checkUserRole } from '@/lib/auth' export default function Layout({ user, admin, }: { user: React.ReactNode admin: React.ReactNode }) { const role = checkUserRole() return <>{role === 'admin' ? admin : user}</> } ### [Tab Groups](#tab-groups) You can add a `layout` inside a slot to allow users to navigate the slot independently. This is useful for creating tabs. For example, the `@analytics` slot has two subpages: `/page-views` and `/visitors`. ![Analytics slot with two subpages and a layout](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes-tab-groups.png&w=3840&q=75)![Analytics slot with two subpages and a layout](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes-tab-groups.png&w=3840&q=75) Within `@analytics`, create a [`layout`](/docs/app/building-your-application/routing/pages-and-layouts) file to share the tabs between the two pages: app/@analytics/layout.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Layout({ children }: { children: React.ReactNode }) { return ( <> <nav> <Link href="/page-views">Page Views</Link> <Link href="/visitors">Visitors</Link> </nav> <div>{children}</div> </> ) } ### [Modals](#modals) Parallel Routes can be used together with [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) to create modals. This allows you to solve common challenges when building modals, such as: * Making the modal content **shareable through a URL**. * **Preserving context** when the page is refreshed, instead of closing the modal. * **Closing the modal on backwards navigation** rather than going to the previous route. * **Reopening the modal on forwards navigation**. Consider the following UI pattern, where a user can open a login modal from a layout using client-side navigation, or access a separate `/login` page: ![Parallel Routes Diagram](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes-auth-modal.png&w=3840&q=75)![Parallel Routes Diagram](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes-auth-modal.png&w=3840&q=75) To implement this pattern, start by creating a `/login` route that renders your **main** login page. ![Parallel Routes Diagram](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes-modal-login-page.png&w=3840&q=75)![Parallel Routes Diagram](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes-modal-login-page.png&w=3840&q=75) app/login/page.tsx TypeScript JavaScriptTypeScript import { Login } from '@/app/ui/login' export default function Page() { return <Login /> } Then, inside the `@auth` slot, add [`default.js`](/docs/app/api-reference/file-conventions/default) file that returns `null`. This ensures that the modal is not rendered when it's not active. app/@auth/default.tsx TypeScript JavaScriptTypeScript export default function Default() { return null } Inside your `@auth` slot, intercept the `/login` route by updating the `/(.)login` folder. Import the `<Modal>` component and its children into the `/(.)login/page.tsx` file: app/@auth/(.)login/page.tsx TypeScript JavaScriptTypeScript import { Modal } from '@/app/ui/modal' import { Login } from '@/app/ui/login' export default function Page() { return ( <Modal> <Login /> </Modal> ) } > **Good to know:** > > * The convention used to intercept the route, e.g. `(.)`, depends on your file-system structure. See [Intercepting Routes convention](/docs/app/building-your-application/routing/intercepting-routes#convention). > * By separating the `<Modal>` functionality from the modal content (`<Login>`), you can ensure any content inside the modal, e.g. [forms](/docs/app/building-your-application/data-fetching/server-actions-and-mutations#forms), are Server Components. See [Interleaving Client and Server Components](/docs/app/building-your-application/rendering/composition-patterns#supported-pattern-passing-server-components-to-client-components-as-props) for more information. #### [Opening the modal](#opening-the-modal) Now, you can leverage the Next.js router to open and close the modal. This ensures the URL is correctly updated when the modal is open, and when navigating backwards and forwards. To open the modal, pass the `@auth` slot as a prop to the parent layout and render it alongside the `children` prop. app/layout.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Layout({ auth, children, }: { auth: React.ReactNode children: React.ReactNode }) { return ( <> <nav> <Link href="/login">Open modal</Link> </nav> <div>{auth}</div> <div>{children}</div> </> ) } When the user clicks the `<Link>`, the modal will open instead of navigating to the `/login` page. However, on refresh or initial load, navigating to `/login` will take the user to the main login page. #### [Closing the modal](#closing-the-modal) You can close the modal by calling `router.back()` or by using the `Link` component. app/ui/modal.tsx TypeScript JavaScriptTypeScript 'use client' import { useRouter } from 'next/navigation' export function Modal({ children }: { children: React.ReactNode }) { const router = useRouter() return ( <> <button onClick={() => { router.back() }} > Close modal </button> <div>{children}</div> </> ) } When using the `Link` component to navigate away from a page that shouldn't render the `@auth` slot anymore, we use a catch-all route that returns `null`. app/ui/modal.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export function Modal({ children }: { children: React.ReactNode }) { return ( <> <Link href="/">Close modal</Link> <div>{children}</div> </> ) } app/@auth/\[...catchAll\]/page.tsx TypeScript JavaScriptTypeScript export default function CatchAll() { return null } > **Good to know:** > > * We use a catch-all route in our `@auth` slot to close the modal because of the behavior described in [Active state and navigation](#active-state-and-navigation). Since client-side navigations to a route that no longer match the slot will remain visible, we need to match the slot to a route that returns `null` to close the modal. > * Other examples could include opening a photo modal in a gallery while also having a dedicated `/photo/[id]` page, or opening a shopping cart in a side modal. > * [View an example](https://github.com/vercel-labs/nextgram) of modals with Intercepted and Parallel Routes. ### [Loading and Error UI](#loading-and-error-ui) Parallel Routes can be streamed independently, allowing you to define independent error and loading states for each route: ![Parallel routes enable custom error and loading states](/_next/image?url=%2Fdocs%2Flight%2Fparallel-routes-cinematic-universe.png&w=3840&q=75)![Parallel routes enable custom error and loading states](/_next/image?url=%2Fdocs%2Fdark%2Fparallel-routes-cinematic-universe.png&w=3840&q=75) See the [Loading UI](/docs/app/building-your-application/routing/loading-ui-and-streaming) and [Error Handling](/docs/app/building-your-application/routing/error-handling) documentation for more information. Next Steps ---------- [ App Router ... File Conventions ### default.js API Reference for the default.js file. ](/docs/app/api-reference/file-conventions/default) [Previous Dynamic Routes ](/docs/app/building-your-application/routing/dynamic-routes) [Next Intercepting Routes ](/docs/app/building-your-application/routing/intercepting-routes) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"02c11b35927137c36ede5c9ffc777bc3\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [ Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Static Metadata](#static-metadata) * [Dynamic Metadata](#dynamic-metadata) * [File-based metadata](#file-based-metadata) * [Behavior](#behavior) * [Default Fields](#default-fields) * [Ordering](#ordering) * [Merging](#merging) * [Overwriting fields](#overwriting-fields) * [Inheriting fields](#inheriting-fields) * [Dynamic Image Generation](#dynamic-image-generation) * [JSON-LD](#json-ld) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/04-metadata.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Metadata Metadata ======== Next.js has a Metadata API that can be used to define your application metadata (e.g. `meta` and `link` tags inside your HTML `head` element) for improved SEO and web shareability. There are two ways you can add metadata to your application: * **Config-based Metadata**: Export a [static `metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object) or a dynamic [`generateMetadata` function](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) in a `layout.js` or `page.js` file. * **File-based Metadata**: Add static or dynamically generated special files to route segments. With both these options, Next.js will automatically generate the relevant `<head>` elements for your pages. You can also create dynamic OG images using the [`ImageResponse`](/docs/app/api-reference/functions/image-response) constructor. [Static Metadata](#static-metadata) ----------------------------------- To define static metadata, export a [`Metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object) from a `layout.js` or static `page.js` file. layout.tsx | page.tsx TypeScript JavaScriptTypeScript import type { Metadata } from 'next' export const metadata: Metadata = { title: '...', description: '...', } export default function Page() {} For all the available options, see the [API Reference](/docs/app/api-reference/functions/generate-metadata). [Dynamic Metadata](#dynamic-metadata) ------------------------------------- You can use `generateMetadata` function to `fetch` metadata that requires dynamic values. app/products/\[id\]/page.tsx TypeScript JavaScriptTypeScript import type { Metadata, ResolvingMetadata } from 'next' type Props = { params: { id: string } searchParams: { [key: string]: string | string[] | undefined } } export async function generateMetadata( { params, searchParams }: Props, parent: ResolvingMetadata ): Promise<Metadata> { // read route params const id = params.id // fetch data const product = await fetch(`https://.../${id}`).then((res) => res.json()) // optionally access and extend (rather than replace) parent metadata const previousImages = (await parent).openGraph?.images || [] return { title: product.title, openGraph: { images: ['/some-specific-page-image.jpg', ...previousImages], }, } } export default function Page({ params, searchParams }: Props) {} For all the available params, see the [API Reference](/docs/app/api-reference/functions/generate-metadata). > **Good to know**: > > * Both static and dynamic metadata through `generateMetadata` are **only supported in Server Components**. > * `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable. > * Next.js will wait for data fetching inside `generateMetadata` to complete before streaming UI to the client. This guarantees the first part of a [streamed response](/docs/app/building-your-application/routing/loading-ui-and-streaming) includes `<head>` tags. [File-based metadata](#file-based-metadata) ------------------------------------------- These special files are available for metadata: * [favicon.ico, apple-icon.jpg, and icon.jpg](/docs/app/api-reference/file-conventions/metadata/app-icons) * [opengraph-image.jpg and twitter-image.jpg](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) You can use these for static metadata, or you can programmatically generate these files with code. For implementation and examples, see the [Metadata Files](/docs/app/api-reference/file-conventions/metadata) API Reference and [Dynamic Image Generation](#dynamic-image-generation). [Behavior](#behavior) --------------------- File-based metadata has the higher priority and will override any config-based metadata. ### [Default Fields](#default-fields) There are two default `meta` tags that are always added even if a route doesn't define metadata: * The [meta charset tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta#attr-charset) sets the character encoding for the website. * The [meta viewport tag](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag) sets the viewport width and scale for the website to adjust for different devices. <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> > **Good to know**: You can overwrite the default [`viewport`](/docs/app/api-reference/functions/generate-metadata#viewport) meta tag. ### [Ordering](#ordering) Metadata is evaluated in order, starting from the root segment down to the segment closest to the final `page.js` segment. For example: 1. `app/layout.tsx` (Root Layout) 2. `app/blog/layout.tsx` (Nested Blog Layout) 3. `app/blog/[slug]/page.tsx` (Blog Page) ### [Merging](#merging) Following the [evaluation order](#ordering), Metadata objects exported from multiple segments in the same route are **shallowly** merged together to form the final metadata output of a route. Duplicate keys are **replaced** based on their ordering. This means metadata with nested fields such as [`openGraph`](/docs/app/api-reference/functions/generate-metadata#opengraph) and [`robots`](/docs/app/api-reference/functions/generate-metadata#robots) that are defined in an earlier segment are **overwritten** by the last segment to define them. #### [Overwriting fields](#overwriting-fields) app/layout.js export const metadata = { title: 'Acme', openGraph: { title: 'Acme', description: 'Acme is a...', }, } app/blog/page.js export const metadata = { title: 'Blog', openGraph: { title: 'Blog', }, } // Output: // <title>Blog</title> // <meta property="og:title" content="Blog" /> In the example above: * `title` from `app/layout.js` is **replaced** by `title` in `app/blog/page.js`. * All `openGraph` fields from `app/layout.js` are **replaced** in `app/blog/page.js` because `app/blog/page.js` sets `openGraph` metadata. Note the absence of `openGraph.description`. If you'd like to share some nested fields between segments while overwriting others, you can pull them out into a separate variable: app/shared-metadata.js export const openGraphImage = { images: ['http://...'] } app/page.js import { openGraphImage } from './shared-metadata' export const metadata = { openGraph: { ...openGraphImage, title: 'Home', }, } app/about/page.js import { openGraphImage } from '../shared-metadata' export const metadata = { openGraph: { ...openGraphImage, title: 'About', }, } In the example above, the OG image is shared between `app/layout.js` and `app/about/page.js` while the titles are different. #### [Inheriting fields](#inheriting-fields) app/layout.js export const metadata = { title: 'Acme', openGraph: { title: 'Acme', description: 'Acme is a...', }, } app/about/page.js export const metadata = { title: 'About', } // Output: // <title>About</title> // <meta property="og:title" content="Acme" /> // <meta property="og:description" content="Acme is a..." /> **Notes** * `title` from `app/layout.js` is **replaced** by `title` in `app/about/page.js`. * All `openGraph` fields from `app/layout.js` are **inherited** in `app/about/page.js` because `app/about/page.js` doesn't set `openGraph` metadata. [Dynamic Image Generation](#dynamic-image-generation) ----------------------------------------------------- The `ImageResponse` constructor allows you to generate dynamic images using JSX and CSS. This is useful for creating social media images such as Open Graph images, Twitter cards, and more. `ImageResponse` uses the [Edge Runtime](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#edge-runtime), and Next.js automatically adds the correct headers to cached images at the edge, helping improve performance and reducing recomputation. To use it, you can import `ImageResponse` from `next/og`: app/about/route.js import { ImageResponse } from 'next/og' export const runtime = 'edge' export async function GET() { return new ImageResponse( ( <div style={{ fontSize: 128, background: 'white', width: '100%', height: '100%', display: 'flex', textAlign: 'center', alignItems: 'center', justifyContent: 'center', }} > Hello world! </div> ), { width: 1200, height: 600, } ) } `ImageResponse` integrates well with other Next.js APIs, including [Route Handlers](/docs/app/building-your-application/routing/route-handlers) and file-based Metadata. For example, you can use `ImageResponse` in a `opengraph-image.tsx` file to generate Open Graph images at build time or dynamically at request time. `ImageResponse` supports common CSS properties including flexbox and absolute positioning, custom fonts, text wrapping, centering, and nested images. [See the full list of supported CSS properties](/docs/app/api-reference/functions/image-response). > **Good to know**: > > * Examples are available in the [Vercel OG Playground](https://og-playground.vercel.app/). > * `ImageResponse` uses [@vercel/og](https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation), [Satori](https://github.com/vercel/satori), and Resvg to convert HTML and CSS into PNG. > * Only the Edge Runtime is supported. The default Node.js runtime will not work. > * Only flexbox and a subset of CSS properties are supported. Advanced layouts (e.g. `display: grid`) will not work. > * Maximum bundle size of `500KB`. The bundle size includes your JSX, CSS, fonts, images, and any other assets. If you exceed the limit, consider reducing the size of any assets or fetching at runtime. > * Only `ttf`, `otf`, and `woff` font formats are supported. To maximize the font parsing speed, `ttf` or `otf` are preferred over `woff`. [JSON-LD](#json-ld) ------------------- [JSON-LD](https://json-ld.org/) is a format for structured data that can be used by search engines to understand your content. For example, you can use it to describe a person, an event, an organization, a movie, a book, a recipe, and many other types of entities. Our current recommendation for JSON-LD is to render structured data as a `<script>` tag in your `layout.js` or `page.js` components. For example: app/products/\[id\]/page.tsx TypeScript JavaScriptTypeScript export default async function Page({ params }) { const product = await getProduct(params.id) const jsonLd = { '@context': 'https://schema.org', '@type': 'Product', name: product.name, image: product.image, description: product.description, } return ( <section> {/* Add JSON-LD to your page */} <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} /> {/* ... */} </section> ) } You can validate and test your structured data with the [Rich Results Test](https://search.google.com/test/rich-results) for Google or the generic [Schema Markup Validator](https://validator.schema.org/). You can type your JSON-LD with TypeScript using community packages like [`schema-dts`](https://www.npmjs.com/package/schema-dts): import { Product, WithContext } from 'schema-dts' const jsonLd: WithContext<Product> = { '@context': 'https://schema.org', '@type': 'Product', name: 'Next.js Sticker', image: 'https://nextjs.org/imgs/sticker.png', description: 'Dynamic at the speed of static.', } Next Steps ---------- View all the Metadata API options. [ App Router ... Functions ### generateMetadata Learn how to add Metadata to your Next.js application for improved search engine optimization (SEO) and web shareability. ](/docs/app/api-reference/functions/generate-metadata)[ App Router ... File Conventions ### Metadata Files API documentation for the metadata file conventions. ](/docs/app/api-reference/file-conventions/metadata)[ App Router ... Functions ### generateViewport API Reference for the generateViewport function. ](/docs/app/api-reference/functions/generate-viewport) [Previous Fonts ](/docs/app/building-your-application/optimizing/fonts) [Next Scripts ](/docs/app/building-your-application/optimizing/scripts) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"6aee9805687e3ae540412251a27fb73b\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/redirect
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [ redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Parameters](#parameters) * [Returns](#returns) * [Example](#example) * [Server Component](#server-component) * [Client Component](#client-component) * [FAQ](#faq) * [Why does redirect use 307 and 308?](#why-does-redirect-use-307-and-308) * [Version History](#version-history) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/redirect.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)redirect redirect ======== The `redirect` function allows you to redirect the user to another URL. `redirect` can be used in [Server Components](/docs/app/building-your-application/rendering/server-components), [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). When used in a [streaming context](/docs/app/building-your-application/routing/loading-ui-and-streaming#what-is-streaming), this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller. If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api-reference/functions/not-found) instead. > **Good to know**: > > * In Server Actions and Route Handlers, `redirect` should be called after the `try/catch` block. > * If you prefer to return a 308 (Permanent) HTTP redirect instead of 307 (Temporary), you can use the [`permanentRedirect` function](/docs/app/api-reference/functions/permanentRedirect) instead. [Parameters](#parameters) ------------------------- The `redirect` function accepts two arguments: redirect(path, type) Parameter Type Description `path` `string` The URL to redirect to. Can be a relative or absolute path. `type` `'replace'` (default) or `'push'` (default in Server Actions) The type of redirect to perform. By default, `redirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. The `type` parameter has no effect when used in Server Components. [Returns](#returns) ------------------- `redirect` does not return any value. [Example](#example) ------------------- ### [Server Component](#server-component) Invoking the `redirect()` function throws a `NEXT_REDIRECT` error and terminates rendering of the route segment in which it was thrown. app/team/\[id\]/page.js import { redirect } from 'next/navigation' async function fetchTeam(id) { const res = await fetch('https://...') if (!res.ok) return undefined return res.json() } export default async function Profile({ params }) { const team = await fetchTeam(params.id) if (!team) { redirect('/login') } // ... } > **Good to know**: `redirect` does not require you to use `return redirect()` as it uses the TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) type. ### [Client Component](#client-component) `redirect` can be used in a Client Component through a Server Action. If you need to use an event handler to redirect the user, you can use the [`useRouter`](/docs/app/api-reference/functions/use-router) hook. app/client-redirect.tsx TypeScript JavaScriptTypeScript 'use client' import { navigate } from './actions' export function ClientRedirect() { return ( <form action={navigate}> <input type="text" name="id" /> <button>Submit</button> </form> ) } app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { redirect } from 'next/navigation' export async function navigate(data: FormData) { redirect(`/posts/${data.get('id')}`) } [FAQ](#faq) ----------- ### [Why does `redirect` use 307 and 308?](#why-does-redirect-use-307-and-308) When using `redirect()` you may notice that the status codes used are `307` for a temporary redirect, and `308` for a permanent redirect. While traditionally a `302` was used for a temporary redirect, and a `301` for a permanent redirect, many browsers changed the request method of the redirect, from a `POST` to `GET` request when using a `302`, regardless of the origins request method. Taking the following example of a redirect from `/users` to `/people`, if you make a `POST` request to `/users` to create a new user, and are conforming to a `302` temporary redirect, the request method will be changed from a `POST` to a `GET` request. This doesn't make sense, as to create a new user, you should be making a `POST` request to `/people`, and not a `GET` request. The introduction of the `307` status code means that the request method is preserved as `POST`. * `302` - Temporary redirect, will change the request method from `POST` to `GET` * `307` - Temporary redirect, will preserve the request method as `POST` The `redirect()` method uses a `307` by default, instead of a `302` temporary redirect, meaning your requests will _always_ be preserved as `POST` requests. [Learn more](https://developer.mozilla.org/docs/Web/HTTP/Redirections) about HTTP Redirects. [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `redirect` introduced. Next Steps ---------- [ App Router ... Functions ### permanentRedirect API Reference for the permanentRedirect function. ](/docs/app/api-reference/functions/permanentRedirect) [Previous permanentRedirect ](/docs/app/api-reference/functions/permanentRedirect) [Next revalidatePath ](/docs/app/api-reference/functions/revalidatePath) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"f43fb231a33d451df87be1d0ebe028a0\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/src-directory
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [ src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/06-src-directory.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)src Directory src Directory ============= As an alternative to having the special Next.js `app` or `pages` directories in the root of your project, Next.js also supports the common pattern of placing application code under the `src` directory. This separates application code from project configuration files which mostly live in the root of a project, which is preferred by some individuals and teams. To use the `src` directory, move the `app` Router folder or `pages` Router folder to `src/app` or `src/pages` respectively. ![An example folder structure with the `src` directory](/_next/image?url=%2Fdocs%2Flight%2Fproject-organization-src-directory.png&w=3840&q=75)![An example folder structure with the `src` directory](/_next/image?url=%2Fdocs%2Fdark%2Fproject-organization-src-directory.png&w=3840&q=75) > **Good to know** > > * The `/public` directory should remain in the root of your project. > * Config files like `package.json`, `next.config.js` and `tsconfig.json` should remain in the root of your project. > * `.env.*` files should remain in the root of your project. > * `src/app` or `src/pages` will be ignored if `app` or `pages` are present in the root directory. > * If you're using `src`, you'll probably also move other application folders such as `/components` or `/lib`. > * If you're using Middleware, ensure it is placed inside the `src` directory. > * If you're using Tailwind CSS, you'll need to add the `/src` prefix to the `tailwind.config.js` file in the [content section](https://tailwindcss.com/docs/content-configuration). > * If you are using TypeScript paths for imports such as `@/*`, you should update the `paths` object in `tsconfig.json` to include `src/`. Next Steps ---------- [ App Router ... Routing ### Project Organization Learn how to organize your Next.js project and colocate files. ](/docs/app/building-your-application/routing/colocation) [Previous MDX ](/docs/app/building-your-application/configuring/mdx) [Next Draft Mode ](/docs/app/building-your-application/configuring/draft-mode) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"a7fd10a4923cf2fe2bec981e41ed061c\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [ Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Convention](#convention) * [Examples](#examples) * [Modals](#modals) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/11-intercepting-routes.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Intercepting Routes Intercepting Routes =================== Intercepting routes allows you to load a route from another part of your application within the current layout. This routing paradigm can be useful when you want to display the content of a route without the user switching to a different context. For example, when clicking on a photo in a feed, you can display the photo in a modal, overlaying the feed. In this case, Next.js intercepts the `/photo/123` route, masks the URL, and overlays it over `/feed`. ![Intercepting routes soft navigation](/_next/image?url=%2Fdocs%2Flight%2Fintercepting-routes-soft-navigate.png&w=3840&q=75)![Intercepting routes soft navigation](/_next/image?url=%2Fdocs%2Fdark%2Fintercepting-routes-soft-navigate.png&w=3840&q=75) However, when navigating to the photo by clicking a shareable URL or by refreshing the page, the entire photo page should render instead of the modal. No route interception should occur. ![Intercepting routes hard navigation](/_next/image?url=%2Fdocs%2Flight%2Fintercepting-routes-hard-navigate.png&w=3840&q=75)![Intercepting routes hard navigation](/_next/image?url=%2Fdocs%2Fdark%2Fintercepting-routes-hard-navigate.png&w=3840&q=75) [Convention](#convention) ------------------------- Intercepting routes can be defined with the `(..)` convention, which is similar to relative path convention `../` but for segments. You can use: * `(.)` to match segments on the **same level** * `(..)` to match segments **one level above** * `(..)(..)` to match segments **two levels above** * `(...)` to match segments from the **root** `app` directory For example, you can intercept the `photo` segment from within the `feed` segment by creating a `(..)photo` directory. ![Intercepting routes folder structure](/_next/image?url=%2Fdocs%2Flight%2Fintercepted-routes-files.png&w=3840&q=75)![Intercepting routes folder structure](/_next/image?url=%2Fdocs%2Fdark%2Fintercepted-routes-files.png&w=3840&q=75) > Note that the `(..)` convention is based on _route segments_, not the file-system. [Examples](#examples) --------------------- ### [Modals](#modals) Intercepting Routes can be used together with [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) to create modals. This allows you to solve common challenges when building modals, such as: * Making the modal content **shareable through a URL**. * **Preserving context** when the page is refreshed, instead of closing the modal. * **Closing the modal on backwards navigation** rather than going to the previous route. * **Reopening the modal on forwards navigation**. Consider the following UI pattern, where a user can open a photo modal from a gallery using client-side navigation, or navigate to the photo page directly from a shareable URL: ![Intercepting routes modal example](/_next/image?url=%2Fdocs%2Flight%2Fintercepted-routes-modal-example.png&w=3840&q=75)![Intercepting routes modal example](/_next/image?url=%2Fdocs%2Fdark%2Fintercepted-routes-modal-example.png&w=3840&q=75) In the above example, the path to the `photo` segment can use the `(..)` matcher since `@modal` is a slot and **not** a segment. This means that the `photo` route is only one segment level higher, despite being two file-system levels higher. See the [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes#modals) documentation for a step-by-step example, or see our [image gallery example](https://github.com/vercel-labs/nextgram). > **Good to know:** > > * Other examples could include opening a login modal in a top navbar while also having a dedicated `/login` page, or opening a shopping cart in a side modal. Next Steps ---------- Learn how to use modals with Intercepted and Parallel Routes. [ App Router ... Routing ### Parallel Routes Simultaneously render one or more pages in the same view that can be navigated independently. A pattern for highly dynamic applications. ](/docs/app/building-your-application/routing/parallel-routes) [Previous Parallel Routes ](/docs/app/building-your-application/routing/parallel-routes) [Next Route Handlers ](/docs/app/building-your-application/routing/route-handlers) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"aa814fedec91f9f6535f48b7e22ff254\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/revalidatePath
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [ revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Parameters](#parameters) * [Returns](#returns) * [Examples](#examples) * [Revalidating A Specific URL](#revalidating-a-specific-url) * [Revalidating A Page Path](#revalidating-a-page-path) * [Revalidating A Layout Path](#revalidating-a-layout-path) * [Revalidating All Data](#revalidating-all-data) * [Server Action](#server-action) * [Route Handler](#route-handler) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/revalidatePath.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)revalidatePath revalidatePath ============== `revalidatePath` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific path. > **Good to know**: > > * `revalidatePath` is available in both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). > * `revalidatePath` only invalidates the cache when the included path is next visited. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited. > * Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#router-cache). This behavior is temporary and will be updated in the future to apply only to the specific path. > * Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/building-your-application/caching#full-route-cache). [Parameters](#parameters) ------------------------- revalidatePath(path: string, type?: 'page' | 'layout'): void; * `path`: Either a string representing the filesystem path associated with the data you want to revalidate (for example, `/product/[slug]/page`), or the literal route segment (for example, `/product/123`). Must be less than 1024 characters. This value is case-sensitive. * `type`: (optional) `'page'` or `'layout'` string to change the type of path to revalidate. If `path` contains a dynamic segment (for example, `/product/[slug]/page`), this parameter is required. [Returns](#returns) ------------------- `revalidatePath` does not return any value. [Examples](#examples) --------------------- ### [Revalidating A Specific URL](#revalidating-a-specific-url) import { revalidatePath } from 'next/cache' revalidatePath('/blog/post-1') This will revalidate one specific URL on the next page visit. ### [Revalidating A Page Path](#revalidating-a-page-path) import { revalidatePath } from 'next/cache' revalidatePath('/blog/[slug]', 'page') // or with route groups revalidatePath('/(main)/post/[slug]', 'page') This will revalidate any URL that matches the provided `page` file on the next page visit. This will _not_ invalidate pages beneath the specific page. For example, `/blog/[slug]` won't invalidate `/blog/[slug]/[author]`. ### [Revalidating A Layout Path](#revalidating-a-layout-path) import { revalidatePath } from 'next/cache' revalidatePath('/blog/[slug]', 'layout') // or with route groups revalidatePath('/(main)/post/[slug]', 'layout') This will revalidate any URL that matches the provided `layout` file on the next page visit. This will cause pages beneath with the same layout to revalidate on the next visit. For example, in the above case, `/blog/[slug]/[another]` would also revalidate on the next visit. ### [Revalidating All Data](#revalidating-all-data) import { revalidatePath } from 'next/cache' revalidatePath('/', 'layout') This will purge the Client-side Router Cache, and revalidate the Data Cache on the next page visit. ### [Server Action](#server-action) app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { revalidatePath } from 'next/cache' export default async function submit() { await submitForm() revalidatePath('/') } ### [Route Handler](#route-handler) app/api/revalidate/route.ts TypeScript JavaScriptTypeScript import { revalidatePath } from 'next/cache' import { NextRequest } from 'next/server' export async function GET(request: NextRequest) { const path = request.nextUrl.searchParams.get('path') if (path) { revalidatePath(path) return Response.json({ revalidated: true, now: Date.now() }) } return Response.json({ revalidated: false, now: Date.now(), message: 'Missing path to revalidate', }) } [Previous redirect ](/docs/app/api-reference/functions/redirect) [Next revalidateTag ](/docs/app/api-reference/functions/revalidateTag) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"daab4bcb4fe0f706343b81cb874b21a1\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions/error
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [ error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Props](#props) * [error](#error) * [error.message](#errormessage) * [error.digest](#errordigest) * [reset](#reset) * [global-error.js](#global-errorjs) * [not-found.js](#not-foundjs) * [Version History](#version-history) * [Learn more about error handling](#learn-more-about-error-handling) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/error.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[File Conventions](/docs/app/api-reference/file-conventions)error.js error.js ======== An **error** file defines an error UI boundary for a route segment. It is useful for catching **unexpected** errors that occur in Server Components and Client Components and displaying a fallback UI. app/dashboard/error.tsx TypeScript JavaScriptTypeScript 'use client' // Error components must be Client Components import { useEffect } from 'react' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { useEffect(() => { // Log the error to an error reporting service console.error(error) }, [error]) return ( <div> <h2>Something went wrong!</h2> <button onClick={ // Attempt to recover by trying to re-render the segment () => reset() } > Try again </button> </div> ) } [Props](#props) --------------- ### [`error`](#error) An instance of an [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) object forwarded to the `error.js` Client Component. #### [`error.message`](#errormessage) The error message. * For errors forwarded from Client Components, this will be the original Error's message. * For errors forwarded from Server Components, this will be a generic error message to avoid leaking sensitive details. `errors.digest` can be used to match the corresponding error in server-side logs. #### [`error.digest`](#errordigest) An automatically generated hash of the error thrown in a Server Component. It can be used to match the corresponding error in server-side logs. ### [`reset`](#reset) A function to reset the error boundary. When executed, the function will try to re-render the Error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render. Can be used to prompt the user to attempt to recover from the error. > **Good to know**: > > * `error.js` boundaries must be **[Client Components](/docs/app/building-your-application/rendering/client-components)**. > * In Production builds, errors forwarded from Server Components will be stripped of specific error details to avoid leaking sensitive information. > * An `error.js` boundary will **not** handle errors thrown in a `layout.js` component in the **same** segment because the error boundary is nested **inside** that layouts component. > * To handle errors for a specific layout, place an `error.js` file in the layouts parent segment. > * To handle errors within the root layout or template, use a variation of `error.js` called `app/global-error.js`. [`global-error.js`](#global-errorjs) ------------------------------------ To specifically handle errors in root `layout.js`, use a variation of `error.js` called `app/global-error.js` located in the root `app` directory. app/global-error.tsx TypeScript JavaScriptTypeScript 'use client' export default function GlobalError({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { return ( <html> <body> <h2>Something went wrong!</h2> <button onClick={() => reset()}>Try again</button> </body> </html> ) } > **Good to know**: > > * `global-error.js` replaces the root `layout.js` when active and so **must** define its own `<html>` and `<body>` tags. > * While designing error UI, you may find it helpful to use the [React Developer Tools](https://react.dev/learn/react-developer-tools) to manually toggle Error boundaries. [not-found.js](#not-foundjs) ---------------------------- The [`not-found`](https://nextjs.org/docs/app/api-reference/file-conventions/not-found) file is used to render UI when the `notFound()` function is thrown within a route segment. [Version History](#version-history) ----------------------------------- Version Changes `v13.1.0` `global-error` introduced. `v13.0.0` `error` introduced. Learn more about error handling ------------------------------- [ App Router ... Routing ### Error Handling Handle runtime errors by automatically wrapping route segments and their nested children in a React Error Boundary. ](/docs/app/building-your-application/routing/error-handling) [Previous default.js ](/docs/app/api-reference/file-conventions/default) [Next instrumentation.js ](/docs/app/api-reference/file-conventions/instrumentation) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"ebcdff7e9d2e8cc6f74f0c68d1895287\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/revalidateTag
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [ revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Parameters](#parameters) * [Returns](#returns) * [Examples](#examples) * [Server Action](#server-action) * [Route Handler](#route-handler) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/revalidateTag.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)revalidateTag revalidateTag ============= `revalidateTag` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific cache tag. > **Good to know**: > > * `revalidateTag` is available in both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). > * `revalidateTag` only invalidates the cache when the path is next visited. This means calling `revalidateTag` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited. [Parameters](#parameters) ------------------------- revalidateTag(tag: string): void; * `tag`: A string representing the cache tag associated with the data you want to revalidate. Must be less than or equal to 256 characters. This value is case-sensitive. You can add tags to `fetch` as follows: fetch(url, { next: { tags: [...] } }); [Returns](#returns) ------------------- `revalidateTag` does not return any value. [Examples](#examples) --------------------- ### [Server Action](#server-action) app/actions.ts TypeScript JavaScriptTypeScript 'use server' import { revalidateTag } from 'next/cache' export default async function submit() { await addPost() revalidateTag('posts') } ### [Route Handler](#route-handler) app/api/revalidate/route.ts TypeScript JavaScriptTypeScript import { NextRequest } from 'next/server' import { revalidateTag } from 'next/cache' export async function GET(request: NextRequest) { const tag = request.nextUrl.searchParams.get('tag') revalidateTag(tag) return Response.json({ revalidated: true, now: Date.now() }) } [Previous revalidatePath ](/docs/app/api-reference/functions/revalidatePath) [Next unstable\_cache ](/docs/app/api-reference/functions/unstable_cache) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"a7e59ebf467d028c02234dbc2323eb98\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [ Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Layout Scripts](#layout-scripts) * [Application Scripts](#application-scripts) * [Strategy](#strategy) * [Offloading Scripts To A Web Worker (Experimental)](#offloading-scripts-to-a-web-worker-experimental) * [Inline Scripts](#inline-scripts) * [Executing Additional Code](#executing-additional-code) * [Additional Attributes](#additional-attributes) * [API Reference](#api-reference) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/05-scripts.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Scripts Script Optimization =================== ### [Layout Scripts](#layout-scripts) To load a third-party script for multiple routes, import `next/script` and include the script directly in your layout component: app/dashboard/layout.tsx TypeScript JavaScriptTypeScript import Script from 'next/script' export default function DashboardLayout({ children, }: { children: React.ReactNode }) { return ( <> <section>{children}</section> <Script src="https://example.com/script.js" /> </> ) } The third-party script is fetched when the folder route (e.g. `dashboard/page.js`) or any nested route (e.g. `dashboard/settings/page.js`) is accessed by the user. Next.js will ensure the script will **only load once**, even if a user navigates between multiple routes in the same layout. ### [Application Scripts](#application-scripts) To load a third-party script for all routes, import `next/script` and include the script directly in your root layout: app/layout.tsx TypeScript JavaScriptTypeScript import Script from 'next/script' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> <Script src="https://example.com/script.js" /> </html> ) } This script will load and execute when _any_ route in your application is accessed. Next.js will ensure the script will **only load once**, even if a user navigates between multiple pages. > **Recommendation**: We recommend only including third-party scripts in specific pages or layouts in order to minimize any unnecessary impact to performance. ### [Strategy](#strategy) Although the default behavior of `next/script` allows you to load third-party scripts in any page or layout, you can fine-tune its loading behavior by using the `strategy` property: * `beforeInteractive`: Load the script before any Next.js code and before any page hydration occurs. * `afterInteractive`: (**default**) Load the script early but after some hydration on the page occurs. * `lazyOnload`: Load the script later during browser idle time. * `worker`: (experimental) Load the script in a web worker. Refer to the [`next/script`](/docs/app/api-reference/components/script#strategy) API reference documentation to learn more about each strategy and their use cases. ### [Offloading Scripts To A Web Worker (Experimental)](#offloading-scripts-to-a-web-worker-experimental) > **Warning:** The `worker` strategy is not yet stable and does not yet work with the [`app`](/docs/app/building-your-application/routing/defining-routes) directory. Use with caution. Scripts that use the `worker` strategy are offloaded and executed in a web worker with [Partytown](https://partytown.builder.io/). This can improve the performance of your site by dedicating the main thread to the rest of your application code. This strategy is still experimental and can only be used if the `nextScriptWorkers` flag is enabled in `next.config.js`: next.config.js module.exports = { experimental: { nextScriptWorkers: true, }, } Then, run `next` (normally `npm run dev` or `yarn dev`) and Next.js will guide you through the installation of the required packages to finish the setup: Terminal npm run dev You'll see instructions like these: Please install Partytown by running `npm install @builder.io/partytown` Once setup is complete, defining `strategy="worker"` will automatically instantiate Partytown in your application and offload the script to a web worker. pages/home.tsx TypeScript JavaScriptTypeScript import Script from 'next/script' export default function Home() { return ( <> <Script src="https://example.com/script.js" strategy="worker" /> </> ) } There are a number of trade-offs that need to be considered when loading a third-party script in a web worker. Please see Partytown's [tradeoffs](https://partytown.builder.io/trade-offs) documentation for more information. ### [Inline Scripts](#inline-scripts) Inline scripts, or scripts not loaded from an external file, are also supported by the Script component. They can be written by placing the JavaScript within curly braces: <Script id="show-banner"> {`document.getElementById('banner').classList.remove('hidden')`} </Script> Or by using the `dangerouslySetInnerHTML` property: <Script id="show-banner" dangerouslySetInnerHTML={{ __html: `document.getElementById('banner').classList.remove('hidden')`, }} /> > **Warning**: An `id` property must be assigned for inline scripts in order for Next.js to track and optimize the script. ### [Executing Additional Code](#executing-additional-code) Event handlers can be used with the Script component to execute additional code after a certain event occurs: * `onLoad`: Execute code after the script has finished loading. * `onReady`: Execute code after the script has finished loading and every time the component is mounted. * `onError`: Execute code if the script fails to load. These handlers will only work when `next/script` is imported and used inside of a [Client Component](/docs/app/building-your-application/rendering/client-components) where `"use client"` is defined as the first line of code: app/page.tsx TypeScript JavaScriptTypeScript 'use client' import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" onLoad={() => { console.log('Script has loaded') }} /> </> ) } Refer to the [`next/script`](/docs/app/api-reference/components/script#onload) API reference to learn more about each event handler and view examples. ### [Additional Attributes](#additional-attributes) There are many DOM attributes that can be assigned to a `<script>` element that are not used by the Script component, like [`nonce`](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/nonce) or [custom data attributes](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/data-*). Including any additional attributes will automatically forward it to the final, optimized `<script>` element that is included in the HTML. app/page.tsx TypeScript JavaScriptTypeScript import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" id="example-script" nonce="XUENAJFW" data-test="script" /> </> ) } API Reference ------------- Learn more about the next/script API. [ App Router ... Components ### <Script> Optimize third-party scripts in your Next.js application using the built-in \`next/script\` Component. ](/docs/app/api-reference/components/script) [Previous Metadata ](/docs/app/building-your-application/optimizing/metadata) [Next Bundle Analyzer ](/docs/app/building-your-application/optimizing/bundle-analyzer) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"90bcdb06ff936a21adb419cddcabd6ff\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [ Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Step 1: Create and access the Route Handler](#step-1-create-and-access-the-route-handler) * [Securely accessing it from your Headless CMS](#securely-accessing-it-from-your-headless-cms) * [Step 2: Update page](#step-2-update-page) * [More Details](#more-details) * [Clear the Draft Mode cookie](#clear-the-draft-mode-cookie) * [Unique per next build](#unique-per-next-build) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/11-draft-mode.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)Draft Mode Draft Mode ========== Static rendering is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to view the draft immediately on your page. You’d want Next.js to render these pages at **request time** instead of build time and fetch the draft content instead of the published content. You’d want Next.js to switch to [dynamic rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) only for this specific case. Next.js has a feature called **Draft Mode** which solves this problem. Here are instructions on how to use it. [Step 1: Create and access the Route Handler](#step-1-create-and-access-the-route-handler) ------------------------------------------------------------------------------------------ First, create a [Route Handler](/docs/app/building-your-application/routing/route-handlers). It can have any name - e.g. `app/api/draft/route.ts` Then, import `draftMode` from `next/headers` and call the `enable()` method. app/api/draft/route.ts TypeScript JavaScriptTypeScript // route handler enabling draft mode import { draftMode } from 'next/headers' export async function GET(request: Request) { draftMode().enable() return new Response('Draft mode is enabled') } This will set a **cookie** to enable draft mode. Subsequent requests containing this cookie will trigger **Draft Mode** changing the behavior for statically generated pages (more on this later). You can test this manually by visiting `/api/draft` and looking at your browser’s developer tools. Notice the `Set-Cookie` response header with a cookie named `__prerender_bypass`. ### [Securely accessing it from your Headless CMS](#securely-accessing-it-from-your-headless-cms) In practice, you’d want to call this Route Handler _securely_ from your headless CMS. The specific steps will vary depending on which headless CMS you’re using, but here are some common steps you could take. These steps assume that the headless CMS you’re using supports setting **custom draft URLs**. If it doesn’t, you can still use this method to secure your draft URLs, but you’ll need to construct and access the draft URL manually. **First**, you should create a **secret token string** using a token generator of your choice. This secret will only be known by your Next.js app and your headless CMS. This secret prevents people who don’t have access to your CMS from accessing draft URLs. **Second**, if your headless CMS supports setting custom draft URLs, specify the following as the draft URL. This assumes that your Route Handler is located at `app/api/draft/route.ts` Terminal https://<your-site>/api/draft?secret=<token>&slug=<path> * `<your-site>` should be your deployment domain. * `<token>` should be replaced with the secret token you generated. * `<path>` should be the path for the page that you want to view. If you want to view `/posts/foo`, then you should use `&slug=/posts/foo`. Your headless CMS might allow you to include a variable in the draft URL so that `<path>` can be set dynamically based on the CMS’s data like so: `&slug=/posts/{entry.fields.slug}` **Finally**, in the Route Handler: * Check that the secret matches and that the `slug` parameter exists (if not, the request should fail). * Call `draftMode.enable()` to set the cookie. * Then redirect the browser to the path specified by `slug`. app/api/draft/route.ts TypeScript JavaScriptTypeScript // route handler with secret and slug import { draftMode } from 'next/headers' import { redirect } from 'next/navigation' export async function GET(request: Request) { // Parse query string parameters const { searchParams } = new URL(request.url) const secret = searchParams.get('secret') const slug = searchParams.get('slug') // Check the secret and next parameters // This secret should only be known to this route handler and the CMS if (secret !== 'MY_SECRET_TOKEN' || !slug) { return new Response('Invalid token', { status: 401 }) } // Fetch the headless CMS to check if the provided `slug` exists // getPostBySlug would implement the required fetching logic to the headless CMS const post = await getPostBySlug(slug) // If the slug doesn't exist prevent draft mode from being enabled if (!post) { return new Response('Invalid slug', { status: 401 }) } // Enable Draft Mode by setting the cookie draftMode().enable() // Redirect to the path from the fetched post // We don't redirect to searchParams.slug as that might lead to open redirect vulnerabilities redirect(post.slug) } If it succeeds, then the browser will be redirected to the path you want to view with the draft mode cookie. [Step 2: Update page](#step-2-update-page) ------------------------------------------ The next step is to update your page to check the value of `draftMode().isEnabled`. If you request a page which has the cookie set, then data will be fetched at **request time** (instead of at build time). Furthermore, the value of `isEnabled` will be `true`. app/page.tsx TypeScript JavaScriptTypeScript // page that fetches data import { draftMode } from 'next/headers' async function getData() { const { isEnabled } = draftMode() const url = isEnabled ? 'https://draft.example.com' : 'https://production.example.com' const res = await fetch(url) return res.json() } export default async function Page() { const { title, desc } = await getData() return ( <main> <h1>{title}</h1> <p>{desc}</p> </main> ) } That's it! If you access the draft Route Handler (with `secret` and `slug`) from your headless CMS or manually, you should now be able to see the draft content. And if you update your draft without publishing, you should be able to view the draft. Set this as the draft URL on your headless CMS or access manually, and you should be able to see the draft. Terminal https://<your-site>/api/draft?secret=<token>&slug=<path> [More Details](#more-details) ----------------------------- ### [Clear the Draft Mode cookie](#clear-the-draft-mode-cookie) By default, the Draft Mode session ends when the browser is closed. To clear the Draft Mode cookie manually, create a Route Handler that calls `draftMode().disable()`: app/api/disable-draft/route.ts TypeScript JavaScriptTypeScript import { draftMode } from 'next/headers' export async function GET(request: Request) { draftMode().disable() return new Response('Draft mode is disabled') } Then, send a request to `/api/disable-draft` to invoke the Route Handler. If calling this route using [`next/link`](/docs/app/api-reference/components/link), you must pass `prefetch={false}` to prevent accidentally deleting the cookie on prefetch. ### [Unique per `next build`](#unique-per-next-build) A new bypass cookie value will be generated each time you run `next build`. This ensures that the bypass cookie can’t be guessed. > **Good to know**: To test Draft Mode locally over HTTP, your browser will need to allow third-party cookies and local storage access. [Previous src Directory ](/docs/app/building-your-application/configuring/src-directory) [Next Content Security Policy ](/docs/app/building-your-application/configuring/content-security-policy) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"db875d574478ce950f493a50a22c4e65\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/bundle-analyzer
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [ Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Installation](#installation) * [Analyzing your bundles](#analyzing-your-bundles) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/06-bundle-analyzer.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Bundle Analyzer Bundle Analyzer =============== [`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) is a plugin for Next.js that helps you manage the size of your JavaScript modules. It generates a visual report of the size of each module and their dependencies. You can use the information to remove large dependencies, split your code, or only load some parts when needed, reducing the amount of data transferred to the client. [Installation](#installation) ----------------------------- Install the plugin by running the following command: npm i @next/bundle-analyzer # or yarn add @next/bundle-analyzer # or pnpm add @next/bundle-analyzer Then, add the bundle analyzer's settings to your `next.config.js`. next.config.js const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true', }) /** @type {import('next').NextConfig} */ const nextConfig = {} module.exports = withBundleAnalyzer(nextConfig) [Analyzing your bundles](#analyzing-your-bundles) ------------------------------------------------- Run the following command to analyze your bundles: ANALYZE=true npm run build # or ANALYZE=true yarn build # or ANALYZE=true pnpm build The report will open three new tabs in your browser, which you can inspect. Doing this regularly while you develop and before deploying your site can help you identify large bundles earlier, and architect your application to be more performant. Next Steps ---------- Learn more about optimizing your application for production. [ App Router ... Deploying ### Production Checklist Recommendations to ensure the best performance and user experience before taking your Next.js application to production. ](/docs/app/building-your-application/deploying/production-checklist) [Previous Scripts ](/docs/app/building-your-application/optimizing/scripts) [Next Lazy Loading ](/docs/app/building-your-application/optimizing/lazy-loading) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"1f2eabf8c6c05a0531cc1f5cb7f9abd3\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions/layout
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [ layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Props](#props) * [children (required)](#children-required) * [params (optional)](#params-optional) * [Good to know](#good-to-know) * [Layouts do not receive searchParams](#layouts-do-not-receive-searchparams) * [Root Layouts](#root-layouts) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/layout.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[File Conventions](/docs/app/api-reference/file-conventions)layout.js layout.js ========= A **layout** is UI that is shared between routes. app/dashboard/layout.tsx TypeScript JavaScriptTypeScript export default function DashboardLayout({ children, }: { children: React.ReactNode }) { return <section>{children}</section> } A **root layout** is the top-most layout in the root `app` directory. It is used to define the `<html>` and `<body>` tags and other globally shared UI. app/layout.tsx TypeScript JavaScriptTypeScript export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> ) } [Props](#props) --------------- ### [`children` (required)](#children-required) Layout components should accept and use a `children` prop. During rendering, `children` will be populated with the route segments the layout is wrapping. These will primarily be the component of a child [Layout](/docs/app/building-your-application/routing/pages-and-layouts#pages) (if it exists) or [Page](/docs/app/building-your-application/routing/pages-and-layouts#pages), but could also be other special files like [Loading](/docs/app/building-your-application/routing/loading-ui-and-streaming) or [Error](/docs/app/building-your-application/routing/error-handling) when applicable. ### [`params` (optional)](#params-optional) The [dynamic route parameters](/docs/app/building-your-application/routing/dynamic-routes) object from the root segment down to that layout. Example URL `params` `app/dashboard/[team]/layout.js` `/dashboard/1` `{ team: '1' }` `app/shop/[tag]/[item]/layout.js` `/shop/1/2` `{ tag: '1', item: '2' }` `app/blog/[...slug]/layout.js` `/blog/1/2` `{ slug: ['1', '2'] }` For example: app/shop/\[tag\]/\[item\]/layout.tsx TypeScript JavaScriptTypeScript export default function ShopLayout({ children, params, }: { children: React.ReactNode params: { tag: string item: string } }) { // URL -> /shop/shoes/nike-air-max-97 // `params` -> { tag: 'shoes', item: 'nike-air-max-97' } return <section>{children}</section> } [Good to know](#good-to-know) ----------------------------- ### [Layouts do not receive `searchParams`](#layouts-do-not-receive-searchparams) Unlike [Pages](/docs/app/api-reference/file-conventions/page), Layout components **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering) which could lead to stale `searchParams` between navigations. When using client-side navigation, Next.js automatically only renders the part of the page below the common layout between two routes. For example, in the following directory structure, `dashboard/layout.tsx` is the common layout for both `/dashboard/settings` and `/dashboard/analytics`: ![File structure showing a dashboard folder nesting a layout.tsx file, and settings and analytics folders with their own pages](/_next/image?url=%2Fdocs%2Flight%2Fshared-dashboard-layout.png&w=3840&q=75)![File structure showing a dashboard folder nesting a layout.tsx file, and settings and analytics folders with their own pages](/_next/image?url=%2Fdocs%2Fdark%2Fshared-dashboard-layout.png&w=3840&q=75) When navigating from `/dashboard/settings` to `/dashboard/analytics`, `page.tsx` in `/dashboard/analytics` will rerender on the server, while `dashboard/layout.tsx` will **not** rerender because it's a common UI shared between the two routes. This performance optimization allows navigation between pages that share a layout to be quicker as only the data fetching and rendering for the page has to run, instead of the entire route that could include shared layouts that fetch their own data. Because `dashboard/layout.tsx` doesn't re-render, the `searchParams` prop in the layout Server Component might become **stale** after navigation. * Instead, use the Page [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop or the [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hook in a Client Component, which is re-rendered on the client with the latest `searchParams`. ### [Root Layouts](#root-layouts) * The `app` directory **must** include a root `app/layout.js`. * The root layout **must** define `<html>` and `<body>` tags. * You should **not** manually add `<head>` tags such as `<title>` and `<meta>` to root layouts. Instead, you should use the [Metadata API](/docs/app/api-reference/functions/generate-metadata) which automatically handles advanced requirements such as streaming and de-duplicating `<head>` elements. * You can use [route groups](/docs/app/building-your-application/routing/route-groups) to create multiple root layouts. * Navigating **across multiple root layouts** will cause a **full page load** (as opposed to a client-side navigation). For example, navigating from `/cart` that uses `app/(shop)/layout.js` to `/blog` that uses `app/(marketing)/layout.js` will cause a full page load. This **only** applies to multiple root layouts. [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `layout` introduced. [Previous instrumentation.js ](/docs/app/api-reference/file-conventions/instrumentation) [Next loading.js ](/docs/app/api-reference/file-conventions/loading) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"0427af96d8e525525013d0d6be7b2283\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/route-handlers
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [ Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Convention](#convention) * [Supported HTTP Methods](#supported-http-methods) * [Extended NextRequest and NextResponse APIs](#extended-nextrequest-and-nextresponse-apis) * [Behavior](#behavior) * [Caching](#caching) * [Opting out of caching](#opting-out-of-caching) * [Route Resolution](#route-resolution) * [Examples](#examples) * [Revalidating Cached Data](#revalidating-cached-data) * [Dynamic Functions](#dynamic-functions) * [Cookies](#cookies) * [Headers](#headers) * [Redirects](#redirects) * [Dynamic Route Segments](#dynamic-route-segments) * [URL Query Parameters](#url-query-parameters) * [Streaming](#streaming) * [Request Body](#request-body) * [Request Body FormData](#request-body-formdata) * [CORS](#cors) * [Webhooks](#webhooks) * [Edge and Node.js Runtimes](#edge-and-nodejs-runtimes) * [Non-UI Responses](#non-ui-responses) * [Segment Config Options](#segment-config-options) * [API Reference](#api-reference) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/12-route-handlers.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Route Handlers Route Handlers ============== Route Handlers allow you to create custom request handlers for a given route using the Web [Request](https://developer.mozilla.org/docs/Web/API/Request) and [Response](https://developer.mozilla.org/docs/Web/API/Response) APIs. ![Route.js Special File](/_next/image?url=%2Fdocs%2Flight%2Froute-special-file.png&w=3840&q=75)![Route.js Special File](/_next/image?url=%2Fdocs%2Fdark%2Froute-special-file.png&w=3840&q=75) > **Good to know**: Route Handlers are only available inside the `app` directory. They are the equivalent of [API Routes](/docs/pages/building-your-application/routing/api-routes) inside the `pages` directory meaning you **do not** need to use API Routes and Route Handlers together. [Convention](#convention) ------------------------- Route Handlers are defined in a [`route.js|ts` file](/docs/app/api-reference/file-conventions/route) inside the `app` directory: app/api/route.ts TypeScript JavaScriptTypeScript export const dynamic = 'force-dynamic' // defaults to auto export async function GET(request: Request) {} Route Handlers can be nested inside the `app` directory, similar to `page.js` and `layout.js`. But there **cannot** be a `route.js` file at the same route segment level as `page.js`. ### [Supported HTTP Methods](#supported-http-methods) The following [HTTP methods](https://developer.mozilla.org/docs/Web/HTTP/Methods) are supported: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, and `OPTIONS`. If an unsupported method is called, Next.js will return a `405 Method Not Allowed` response. ### [Extended `NextRequest` and `NextResponse` APIs](#extended-nextrequest-and-nextresponse-apis) In addition to supporting native [Request](https://developer.mozilla.org/docs/Web/API/Request) and [Response](https://developer.mozilla.org/docs/Web/API/Response). Next.js extends them with [`NextRequest`](/docs/app/api-reference/functions/next-request) and [`NextResponse`](/docs/app/api-reference/functions/next-response) to provide convenient helpers for advanced use cases. [Behavior](#behavior) --------------------- ### [Caching](#caching) Route Handlers are cached by default when using the `GET` method with the `Response` object. app/items/route.ts TypeScript JavaScriptTypeScript export async function GET() { const res = await fetch('https://data.mongodb-api.com/...', { headers: { 'Content-Type': 'application/json', 'API-Key': process.env.DATA_API_KEY, }, }) const data = await res.json() return Response.json({ data }) } > **TypeScript Warning:** `Response.json()` is only valid from TypeScript 5.2. If you use a lower TypeScript version, you can use [`NextResponse.json()`](/docs/app/api-reference/functions/next-response#json) for typed responses instead. ### [Opting out of caching](#opting-out-of-caching) You can opt out of caching by: * Using the `Request` object with the `GET` method. * Using any of the other HTTP methods. * Using [Dynamic Functions](#dynamic-functions) like `cookies` and `headers`. * The [Segment Config Options](#segment-config-options) manually specifies dynamic mode. For example: app/products/api/route.ts TypeScript JavaScriptTypeScript export async function GET(request: Request) { const { searchParams } = new URL(request.url) const id = searchParams.get('id') const res = await fetch(`https://data.mongodb-api.com/product/${id}`, { headers: { 'Content-Type': 'application/json', 'API-Key': process.env.DATA_API_KEY!, }, }) const product = await res.json() return Response.json({ product }) } Similarly, the `POST` method will cause the Route Handler to be evaluated dynamically. app/items/route.ts TypeScript JavaScriptTypeScript export async function POST() { const res = await fetch('https://data.mongodb-api.com/...', { method: 'POST', headers: { 'Content-Type': 'application/json', 'API-Key': process.env.DATA_API_KEY!, }, body: JSON.stringify({ time: new Date().toISOString() }), }) const data = await res.json() return Response.json(data) } > **Good to know**: Like API Routes, Route Handlers can be used for cases like handling form submissions. A new abstraction for [handling forms and mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) that integrates deeply with React is being worked on. ### [Route Resolution](#route-resolution) You can consider a `route` the lowest level routing primitive. * They **do not** participate in layouts or client-side navigations like `page`. * There **cannot** be a `route.js` file at the same route as `page.js`. Page Route Result `app/page.js` `app/route.js` Conflict `app/page.js` `app/api/route.js` Valid `app/[user]/page.js` `app/api/route.js` Valid Each `route.js` or `page.js` file takes over all HTTP verbs for that route. app/page.js export default function Page() { return <h1>Hello, Next.js!</h1> } // ❌ Conflict // `app/route.js` export async function POST(request) {} [Examples](#examples) --------------------- The following examples show how to combine Route Handlers with other Next.js APIs and features. ### [Revalidating Cached Data](#revalidating-cached-data) You can [revalidate cached data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) using the [`next.revalidate`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) option: app/items/route.ts TypeScript JavaScriptTypeScript export async function GET() { const res = await fetch('https://data.mongodb-api.com/...', { next: { revalidate: 60 }, // Revalidate every 60 seconds }) const data = await res.json() return Response.json(data) } Alternatively, you can use the [`revalidate` segment config option](/docs/app/api-reference/file-conventions/route-segment-config#revalidate): export const revalidate = 60 ### [Dynamic Functions](#dynamic-functions) Route Handlers can be used with dynamic functions from Next.js, like [`cookies`](/docs/app/api-reference/functions/cookies) and [`headers`](/docs/app/api-reference/functions/headers). #### [Cookies](#cookies) You can read or set cookies with [`cookies`](/docs/app/api-reference/functions/cookies) from `next/headers`. This server function can be called directly in a Route Handler, or nested inside of another function. Alternatively, you can return a new `Response` using the [`Set-Cookie`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie) header. app/api/route.ts TypeScript JavaScriptTypeScript import { cookies } from 'next/headers' export async function GET(request: Request) { const cookieStore = cookies() const token = cookieStore.get('token') return new Response('Hello, Next.js!', { status: 200, headers: { 'Set-Cookie': `token=${token.value}` }, }) } You can also use the underlying Web APIs to read cookies from the request ([`NextRequest`](/docs/app/api-reference/functions/next-request)): app/api/route.ts TypeScript JavaScriptTypeScript import { type NextRequest } from 'next/server' export async function GET(request: NextRequest) { const token = request.cookies.get('token') } #### [Headers](#headers) You can read headers with [`headers`](/docs/app/api-reference/functions/headers) from `next/headers`. This server function can be called directly in a Route Handler, or nested inside of another function. This `headers` instance is read-only. To set headers, you need to return a new `Response` with new `headers`. app/api/route.ts TypeScript JavaScriptTypeScript import { headers } from 'next/headers' export async function GET(request: Request) { const headersList = headers() const referer = headersList.get('referer') return new Response('Hello, Next.js!', { status: 200, headers: { referer: referer }, }) } You can also use the underlying Web APIs to read headers from the request ([`NextRequest`](/docs/app/api-reference/functions/next-request)): app/api/route.ts TypeScript JavaScriptTypeScript import { type NextRequest } from 'next/server' export async function GET(request: NextRequest) { const requestHeaders = new Headers(request.headers) } ### [Redirects](#redirects) app/api/route.ts TypeScript JavaScriptTypeScript import { redirect } from 'next/navigation' export async function GET(request: Request) { redirect('https://nextjs.org/') } ### [Dynamic Route Segments](#dynamic-route-segments) > We recommend reading the [Defining Routes](/docs/app/building-your-application/routing/defining-routes) page before continuing. Route Handlers can use [Dynamic Segments](/docs/app/building-your-application/routing/dynamic-routes) to create request handlers from dynamic data. app/items/\[slug\]/route.ts TypeScript JavaScriptTypeScript export async function GET( request: Request, { params }: { params: { slug: string } } ) { const slug = params.slug // 'a', 'b', or 'c' } Route Example URL `params` `app/items/[slug]/route.js` `/items/a` `{ slug: 'a' }` `app/items/[slug]/route.js` `/items/b` `{ slug: 'b' }` `app/items/[slug]/route.js` `/items/c` `{ slug: 'c' }` ### [URL Query Parameters](#url-query-parameters) The request object passed to the Route Handler is a `NextRequest` instance, which has [some additional convenience methods](/docs/app/api-reference/functions/next-request#nexturl), including for more easily handling query parameters. app/api/search/route.ts TypeScript JavaScriptTypeScript import { type NextRequest } from 'next/server' export function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams const query = searchParams.get('query') // query is "hello" for /api/search?query=hello } ### [Streaming](#streaming) Streaming is commonly used in combination with Large Language Models (LLMs), such as OpenAI, for AI-generated content. Learn more about the [AI SDK](https://sdk.vercel.ai/docs). app/api/chat/route.ts TypeScript JavaScriptTypeScript import OpenAI from 'openai' import { OpenAIStream, StreamingTextResponse } from 'ai' const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }) export const runtime = 'edge' export async function POST(req: Request) { const { messages } = await req.json() const response = await openai.chat.completions.create({ model: 'gpt-3.5-turbo', stream: true, messages, }) const stream = OpenAIStream(response) return new StreamingTextResponse(stream) } These abstractions use the Web APIs to create a stream. You can also use the underlying Web APIs directly. app/api/route.ts TypeScript JavaScriptTypeScript // https://developer.mozilla.org/docs/Web/API/ReadableStream#convert_async_iterator_to_stream function iteratorToStream(iterator: any) { return new ReadableStream({ async pull(controller) { const { value, done } = await iterator.next() if (done) { controller.close() } else { controller.enqueue(value) } }, }) } function sleep(time: number) { return new Promise((resolve) => { setTimeout(resolve, time) }) } const encoder = new TextEncoder() async function* makeIterator() { yield encoder.encode('<p>One</p>') await sleep(200) yield encoder.encode('<p>Two</p>') await sleep(200) yield encoder.encode('<p>Three</p>') } export async function GET() { const iterator = makeIterator() const stream = iteratorToStream(iterator) return new Response(stream) } ### [Request Body](#request-body) You can read the `Request` body using the standard Web API methods: app/items/route.ts TypeScript JavaScriptTypeScript export async function POST(request: Request) { const res = await request.json() return Response.json({ res }) } ### [Request Body FormData](#request-body-formdata) You can read the `FormData` using the `request.formData()` function: app/items/route.ts TypeScript JavaScriptTypeScript export async function POST(request: Request) { const formData = await request.formData() const name = formData.get('name') const email = formData.get('email') return Response.json({ name, email }) } Since `formData` data are all strings, you may want to use [`zod-form-data`](https://www.npmjs.com/zod-form-data) to validate the request and retrieve data in the format you prefer (e.g. `number`). ### [CORS](#cors) You can set CORS headers for a specific Route Handler using the standard Web API methods: app/api/route.ts TypeScript JavaScriptTypeScript export const dynamic = 'force-dynamic' // defaults to auto export async function GET(request: Request) { return new Response('Hello, Next.js!', { status: 200, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }, }) } > **Good to know**: > > * To add CORS headers to multiple Route Handlers, you can use [Middleware](/docs/app/building-your-application/routing/middleware#cors) or the [`next.config.js` file](/docs/app/api-reference/next-config-js/headers#cors). > * Alternatively, see our [CORS example](https://github.com/vercel/examples/blob/main/edge-functions/cors/lib/cors.ts) package. ### [Webhooks](#webhooks) You can use a Route Handler to receive webhooks from third-party services: app/api/route.ts TypeScript JavaScriptTypeScript export async function POST(request: Request) { try { const text = await request.text() // Process the webhook payload } catch (error) { return new Response(`Webhook error: ${error.message}`, { status: 400, }) } return new Response('Success!', { status: 200, }) } Notably, unlike API Routes with the Pages Router, you do not need to use `bodyParser` to use any additional configuration. ### [Edge and Node.js Runtimes](#edge-and-nodejs-runtimes) Route Handlers have an isomorphic Web API to support both Edge and Node.js runtimes seamlessly, including support for streaming. Since Route Handlers use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) as Pages and Layouts, they support long-awaited features like general-purpose [statically regenerated](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) Route Handlers. You can use the `runtime` segment config option to specify the runtime: export const runtime = 'edge' // 'nodejs' is the default ### [Non-UI Responses](#non-ui-responses) You can use Route Handlers to return non-UI content. Note that [`sitemap.xml`](/docs/app/api-reference/file-conventions/metadata/sitemap#generating-a-sitemap-using-code-js-ts), [`robots.txt`](/docs/app/api-reference/file-conventions/metadata/robots#generate-a-robots-file), [`app icons`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx), and [open graph images](/docs/app/api-reference/file-conventions/metadata/opengraph-image) all have built-in support. app/rss.xml/route.ts TypeScript JavaScriptTypeScript export const dynamic = 'force-dynamic' // defaults to auto export async function GET() { return new Response( `<?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0"> <channel> <title>Next.js Documentation</title> <link>https://nextjs.org/docs</link> <description>The React Framework for the Web</description> </channel> </rss>`, { headers: { 'Content-Type': 'text/xml', }, } ) } ### [Segment Config Options](#segment-config-options) Route Handlers use the same [route segment configuration](/docs/app/api-reference/file-conventions/route-segment-config) as pages and layouts. app/items/route.ts TypeScript JavaScriptTypeScript export const dynamic = 'auto' export const dynamicParams = true export const revalidate = false export const fetchCache = 'auto' export const runtime = 'nodejs' export const preferredRegion = 'auto' See the [API reference](/docs/app/api-reference/file-conventions/route-segment-config) for more details. API Reference ------------- Learn more about the route.js file. [ App Router ... File Conventions ### route.js API reference for the route.js special file. ](/docs/app/api-reference/file-conventions/route) [Previous Intercepting Routes ](/docs/app/building-your-application/routing/intercepting-routes) [Next Middleware ](/docs/app/building-your-application/routing/middleware) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"8c610902475c336d3d0a9718399e236d\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [ instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Config Option](#config-option) * [Exports](#exports) * [register (required)](#register-required) * [Version History](#version-history) * [Learn more about Instrumentation](#learn-more-about-instrumentation) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/instrumentation.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[File Conventions](/docs/app/api-reference/file-conventions)instrumentation.js instrumentation.js ================== The `instrumentation.js|ts` file is used to integrate monitoring and logging tools into your application. This allows you to track the performance and behavior of your application, and to debug issues in production. To use it, place the file in the **root** of your application or inside a [`src` folder](/docs/app/building-your-application/configuring/src-directory) if using one. [Config Option](#config-option) ------------------------------- Instrumentation is currently an experimental feature, to use the `instrumentation` file, you must explicitly opt-in by defining [`experimental.instrumentationHook = true;`](/docs/app/api-reference/next-config-js/instrumentationHook) in your `next.config.js`: next.config.js module.exports = { experimental: { instrumentationHook: true, }, } [Exports](#exports) ------------------- ### [`register` (required)](#register-required) The file exports a `register` function that is called **once** when a new Next.js server instance is initiated. `register` can be an async function. instrumentation.ts TypeScript JavaScriptTypeScript import { registerOTel } from '@vercel/otel' export function register() { registerOTel('next-app') } [Version History](#version-history) ----------------------------------- Version Changes `v14.0.4` Turbopack support for `instrumentation` `v13.2.0` `instrumentation` introduced as an experimental feature Learn more about Instrumentation -------------------------------- [ App Router ... Optimizing ### Instrumentation Learn how to use instrumentation to run code at server startup in your Next.js app ](/docs/app/building-your-application/optimizing/instrumentation) [Previous error.js ](/docs/app/api-reference/file-conventions/error) [Next layout.js ](/docs/app/api-reference/file-conventions/layout) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"ffe93666bbe6a23502791ae5a2fa06e1\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/middleware
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [ Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Use Cases](#use-cases) * [Convention](#convention) * [Example](#example) * [Matching Paths](#matching-paths) * [Matcher](#matcher) * [Conditional Statements](#conditional-statements) * [NextResponse](#nextresponse) * [Using Cookies](#using-cookies) * [Setting Headers](#setting-headers) * [CORS](#cors) * [Producing a Response](#producing-a-response) * [waitUntil and NextFetchEvent](#waituntil-and-nextfetchevent) * [Advanced Middleware Flags](#advanced-middleware-flags) * [Runtime](#runtime) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/13-middleware.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Middleware Middleware ========== Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly. Middleware runs before cached content and routes are matched. See [Matching Paths](#matching-paths) for more details. [Use Cases](#use-cases) ----------------------- Integrating Middleware into your application can lead to significant improvements in performance, security, and user experience. Some common scenarios where Middleware is particularly effective include: * Authentication and Authorization: Ensure user identity and check session cookies before granting access to specific pages or API routes. * Server-Side Redirects: Redirect users at the server level based on certain conditions (e.g., locale, user role). * Path Rewriting: Support A/B testing, feature rollouts, or legacy paths by dynamically rewriting paths to API routes or pages based on request properties. * Bot Detection: Protect your resources by detecting and blocking bot traffic. * Logging and Analytics: Capture and analyze request data for insights before processing by the page or API. * Feature Flagging: Enable or disable features dynamically for seamless feature rollouts or testing. Recognizing situations where middleware may not be the optimal approach is just as crucial. Here are some scenarios to be mindful of: * Complex Data Fetching and Manipulation: Middleware is not designed for direct data fetching or manipulation, this should be done within Route Handlers or server-side utilities instead. * Heavy Computational Tasks: Middleware should be lightweight and respond quickly or it can cause delays in page load. Heavy computational tasks or long-running processes should be done within dedicated Route Handlers. * Extensive Session Management: While Middleware can manage basic session tasks, extensive session management should be managed by dedicated authentication services or within Route Handlers. * Direct Database Operations: Performing direct database operations within Middleware is not recommended. Database interactions should done within Route Handlers or server-side utilities. [Convention](#convention) ------------------------- Use the file `middleware.ts` (or `.js`) in the root of your project to define Middleware. For example, at the same level as `pages` or `app`, or inside `src` if applicable. > **Note**: While only one `middleware.ts` file is supported per project, you can still organize your middleware logic modularly. Break out middleware functionalities into separate `.ts` or `.js` files and import them into your main `middleware.ts` file. This allows for cleaner management of route-specific middleware, aggregated in the `middleware.ts` for centralized control. By enforcing a single middleware file, it simplifies configuration, prevents potential conflicts, and optimizes performance by avoiding multiple middleware layers. [Example](#example) ------------------- middleware.ts TypeScript JavaScriptTypeScript import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' // This function can be marked `async` if using `await` inside export function middleware(request: NextRequest) { return NextResponse.redirect(new URL('/home', request.url)) } // See "Matching Paths" below to learn more export const config = { matcher: '/about/:path*', } [Matching Paths](#matching-paths) --------------------------------- Middleware will be invoked for **every route in your project**. Given this, it's crucial to use matchers to precisely target or exclude specific routes. The following is the execution order: 1. `headers` from `next.config.js` 2. `redirects` from `next.config.js` 3. Middleware (`rewrites`, `redirects`, etc.) 4. `beforeFiles` (`rewrites`) from `next.config.js` 5. Filesystem routes (`public/`, `_next/static/`, `pages/`, `app/`, etc.) 6. `afterFiles` (`rewrites`) from `next.config.js` 7. Dynamic Routes (`/blog/[slug]`) 8. `fallback` (`rewrites`) from `next.config.js` There are two ways to define which paths Middleware will run on: 1. [Custom matcher config](#matcher) 2. [Conditional statements](#conditional-statements) ### [Matcher](#matcher) `matcher` allows you to filter Middleware to run on specific paths. middleware.js export const config = { matcher: '/about/:path*', } You can match a single path or multiple paths with an array syntax: middleware.js export const config = { matcher: ['/about/:path*', '/dashboard/:path*'], } The `matcher` config allows full regex so matching like negative lookaheads or character matching is supported. An example of a negative lookahead to match all except specific paths can be seen here: middleware.js export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], } You can also bypass Middleware for certain requests by using the `missing` or `has` arrays, or a combination of both: middleware.js export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ { source: '/((?!api|_next/static|_next/image|favicon.ico).*)', missing: [ { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }, ], }, { source: '/((?!api|_next/static|_next/image|favicon.ico).*)', has: [ { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }, ], }, { source: '/((?!api|_next/static|_next/image|favicon.ico).*)', has: [{ type: 'header', key: 'x-present' }], missing: [{ type: 'header', key: 'x-missing', value: 'prefetch' }], }, ], } > **Good to know**: The `matcher` values need to be constants so they can be statically analyzed at build-time. Dynamic values such as variables will be ignored. Configured matchers: 1. MUST start with `/` 2. Can include named parameters: `/about/:path` matches `/about/a` and `/about/b` but not `/about/a/c` 3. Can have modifiers on named parameters (starting with `:`): `/about/:path*` matches `/about/a/b/c` because `*` is _zero or more_. `?` is _zero or one_ and `+` _one or more_ 4. Can use regular expression enclosed in parenthesis: `/about/(.*)` is the same as `/about/:path*` Read more details on [path-to-regexp](https://github.com/pillarjs/path-to-regexp#path-to-regexp-1) documentation. > **Good to know**: For backward compatibility, Next.js always considers `/public` as `/public/index`. Therefore, a matcher of `/public/:path` will match. ### [Conditional Statements](#conditional-statements) middleware.ts TypeScript JavaScriptTypeScript import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { if (request.nextUrl.pathname.startsWith('/about')) { return NextResponse.rewrite(new URL('/about-2', request.url)) } if (request.nextUrl.pathname.startsWith('/dashboard')) { return NextResponse.rewrite(new URL('/dashboard/user', request.url)) } } [NextResponse](#nextresponse) ----------------------------- The `NextResponse` API allows you to: * `redirect` the incoming request to a different URL * `rewrite` the response by displaying a given URL * Set request headers for API Routes, `getServerSideProps`, and `rewrite` destinations * Set response cookies * Set response headers To produce a response from Middleware, you can: 1. `rewrite` to a route ([Page](/docs/app/building-your-application/routing/pages-and-layouts) or [Route Handler](/docs/app/building-your-application/routing/route-handlers)) that produces a response 2. return a `NextResponse` directly. See [Producing a Response](#producing-a-response) [Using Cookies](#using-cookies) ------------------------------- Cookies are regular headers. On a `Request`, they are stored in the `Cookie` header. On a `Response` they are in the `Set-Cookie` header. Next.js provides a convenient way to access and manipulate these cookies through the `cookies` extension on `NextRequest` and `NextResponse`. 1. For incoming requests, `cookies` comes with the following methods: `get`, `getAll`, `set`, and `delete` cookies. You can check for the existence of a cookie with `has` or remove all cookies with `clear`. 2. For outgoing responses, `cookies` have the following methods `get`, `getAll`, `set`, and `delete`. middleware.ts TypeScript JavaScriptTypeScript import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { // Assume a "Cookie:nextjs=fast" header to be present on the incoming request // Getting cookies from the request using the `RequestCookies` API let cookie = request.cookies.get('nextjs') console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' } const allCookies = request.cookies.getAll() console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }] request.cookies.has('nextjs') // => true request.cookies.delete('nextjs') request.cookies.has('nextjs') // => false // Setting cookies on the response using the `ResponseCookies` API const response = NextResponse.next() response.cookies.set('vercel', 'fast') response.cookies.set({ name: 'vercel', value: 'fast', path: '/', }) cookie = response.cookies.get('vercel') console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' } // The outgoing response will have a `Set-Cookie:vercel=fast;path=/` header. return response } [Setting Headers](#setting-headers) ----------------------------------- You can set request and response headers using the `NextResponse` API (setting _request_ headers is available since Next.js v13.0.0). middleware.ts TypeScript JavaScriptTypeScript import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { // Clone the request headers and set a new header `x-hello-from-middleware1` const requestHeaders = new Headers(request.headers) requestHeaders.set('x-hello-from-middleware1', 'hello') // You can also set request headers in NextResponse.rewrite const response = NextResponse.next({ request: { // New request headers headers: requestHeaders, }, }) // Set a new response header `x-hello-from-middleware2` response.headers.set('x-hello-from-middleware2', 'hello') return response } > **Good to know**: Avoid setting large headers as it might cause [431 Request Header Fields Too Large](https://developer.mozilla.org/docs/Web/HTTP/Status/431) error depending on your backend web server configuration. ### [CORS](#cors) You can set CORS headers in Middleware to allow cross-origin requests, including [simple](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests) and [preflighted](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests) requests. middleware.ts TypeScript JavaScriptTypeScript import { NextRequest, NextResponse } from 'next/server' const allowedOrigins = ['https://acme.com', 'https://my-app.org'] const corsOptions = { 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', } export function middleware(request: NextRequest) { // Check the origin from the request const origin = request.headers.get('origin') ?? '' const isAllowedOrigin = allowedOrigins.includes(origin) // Handle preflighted requests const isPreflight = request.method === 'OPTIONS' if (isPreflight) { const preflightHeaders = { ...(isAllowedOrigin && { 'Access-Control-Allow-Origin': origin }), ...corsOptions, } return NextResponse.json({}, { headers: preflightHeaders }) } // Handle simple requests const response = NextResponse.next() if (isAllowedOrigin) { response.headers.set('Access-Control-Allow-Origin', origin) } Object.entries(corsOptions).forEach(([key, value]) => { response.headers.set(key, value) }) return response } export const config = { matcher: '/api/:path*', } > **Good to know:** You can configure CORS headers for individual routes in [Route Handlers](/docs/app/building-your-application/routing/route-handlers#cors). [Producing a Response](#producing-a-response) --------------------------------------------- You can respond from Middleware directly by returning a `Response` or `NextResponse` instance. (This is available since [Next.js v13.1.0](https://nextjs.org/blog/next-13-1#nextjs-advanced-middleware)) middleware.ts TypeScript JavaScriptTypeScript import { NextRequest } from 'next/server' import { isAuthenticated } from '@lib/auth' // Limit the middleware to paths starting with `/api/` export const config = { matcher: '/api/:function*', } export function middleware(request: NextRequest) { // Call our authentication function to check the request if (!isAuthenticated(request)) { // Respond with JSON indicating an error message return Response.json( { success: false, message: 'authentication failed' }, { status: 401 } ) } } ### [`waitUntil` and `NextFetchEvent`](#waituntil-and-nextfetchevent) The `NextFetchEvent` object extends the native [`FetchEvent`](https://developer.mozilla.org/docs/Web/API/FetchEvent) object, and includes the [`waitUntil()`](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) method. The `waitUntil()` method takes a promise as an argument, and extends the lifetime of the Middleware until the promise settles. This is useful for performing work in the background. middleware.ts import { NextResponse } from 'next/server' import type { NextFetchEvent, NextRequest } from 'next/server' export function middleware(req: NextRequest, event: NextFetchEvent) { event.waitUntil( fetch('https://my-analytics-platform.com', { method: 'POST', body: JSON.stringify({ pathname: req.nextUrl.pathname }), }) ) return NextResponse.next() } [Advanced Middleware Flags](#advanced-middleware-flags) ------------------------------------------------------- In `v13.1` of Next.js two additional flags were introduced for middleware, `skipMiddlewareUrlNormalize` and `skipTrailingSlashRedirect` to handle advanced use cases. `skipTrailingSlashRedirect` disables Next.js redirects for adding or removing trailing slashes. This allows custom handling inside middleware to maintain the trailing slash for some paths but not others, which can make incremental migrations easier. next.config.js module.exports = { skipTrailingSlashRedirect: true, } middleware.js const legacyPrefixes = ['/docs', '/blog'] export default async function middleware(req) { const { pathname } = req.nextUrl if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) { return NextResponse.next() } // apply trailing slash handling if ( !pathname.endsWith('/') && !pathname.match(/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/) ) { req.nextUrl.pathname += '/' return NextResponse.redirect(req.nextUrl) } } `skipMiddlewareUrlNormalize` allows for disabling the URL normalization in Next.js to make handling direct visits and client-transitions the same. In some advanced cases, this option provides full control by using the original URL. next.config.js module.exports = { skipMiddlewareUrlNormalize: true, } middleware.js export default async function middleware(req) { const { pathname } = req.nextUrl // GET /_next/data/build-id/hello.json console.log(pathname) // with the flag this now /_next/data/build-id/hello.json // without the flag this would be normalized to /hello } [Runtime](#runtime) ------------------- Middleware currently only supports the [Edge runtime](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). The Node.js runtime can not be used. [Version History](#version-history) ----------------------------------- Version Changes `v13.1.0` Advanced Middleware flags added `v13.0.0` Middleware can modify request headers, response headers, and send responses `v12.2.0` Middleware is stable, please see the [upgrade guide](/docs/messages/middleware-upgrade-guide) `v12.0.9` Enforce absolute URLs in Edge Runtime ([PR](https://github.com/vercel/next.js/pull/33410)) `v12.0.0` Middleware (Beta) added [Previous Route Handlers ](/docs/app/building-your-application/routing/route-handlers) [Next Internationalization ](/docs/app/building-your-application/routing/internationalization) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"3d771b2063692801d2d8f38180985d25\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [ Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Nonces](#nonces) * [Why use a nonce?](#why-use-a-nonce) * [Adding a nonce with Middleware](#adding-a-nonce-with-middleware) * [Reading the nonce](#reading-the-nonce) * [Without Nonces](#without-nonces) * [Version History](#version-history) * [Next Steps](#next-steps) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/07-configuring/15-content-security-policy.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Configuring](/docs/app/building-your-application/configuring)Content Security Policy Content Security Policy ======================= [Content Security Policy (CSP)](https://developer.mozilla.org/docs/Web/HTTP/CSP) is important to guard your Next.js application against various security threats such as cross-site scripting (XSS), clickjacking, and other code injection attacks. By using CSP, developers can specify which origins are permissible for content sources, scripts, stylesheets, images, fonts, objects, media (audio, video), iframes, and more. Examples * [Strict CSP](https://github.com/vercel/next.js/tree/canary/examples/with-strict-csp) [Nonces](#nonces) ----------------- A [nonce](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/nonce) is a unique, random string of characters created for a one-time use. It is used in conjunction with CSP to selectively allow certain inline scripts or styles to execute, bypassing strict CSP directives. ### [Why use a nonce?](#why-use-a-nonce) Even though CSPs are designed to block malicious scripts, there are legitimate scenarios where inline scripts are necessary. In such cases, nonces offer a way to allow these scripts to execute if they have the correct nonce. ### [Adding a nonce with Middleware](#adding-a-nonce-with-middleware) [Middleware](/docs/app/building-your-application/routing/middleware) enables you to add headers and generate nonces before the page renders. Every time a page is viewed, a fresh nonce should be generated. This means that you **must use dynamic rendering to add nonces**. For example: middleware.ts TypeScript JavaScriptTypeScript import { NextRequest, NextResponse } from 'next/server' export function middleware(request: NextRequest) { const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const cspHeader = ` default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; style-src 'self' 'nonce-${nonce}'; img-src 'self' blob: data:; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; ` // Replace newline characters and spaces const contentSecurityPolicyHeaderValue = cspHeader .replace(/\s{2,}/g, ' ') .trim() const requestHeaders = new Headers(request.headers) requestHeaders.set('x-nonce', nonce) requestHeaders.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) const response = NextResponse.next({ request: { headers: requestHeaders, }, }) response.headers.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) return response } By default, Middleware runs on all requests. You can filter Middleware to run on specific paths using a [`matcher`](/docs/app/building-your-application/routing/middleware#matcher). We recommend ignoring matching prefetches (from `next/link`) and static assets that don't need the CSP header. middleware.ts TypeScript JavaScriptTypeScript export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ { source: '/((?!api|_next/static|_next/image|favicon.ico).*)', missing: [ { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }, ], }, ], } ### [Reading the nonce](#reading-the-nonce) You can now read the nonce from a [Server Component](/docs/app/building-your-application/rendering/server-components) using [`headers`](/docs/app/api-reference/functions/headers): app/page.tsx TypeScript JavaScriptTypeScript import { headers } from 'next/headers' import Script from 'next/script' export default function Page() { const nonce = headers().get('x-nonce') return ( <Script src="https://www.googletagmanager.com/gtag/js" strategy="afterInteractive" nonce={nonce} /> ) } [Without Nonces](#without-nonces) --------------------------------- For applications that do not require nonces, you can set the CSP header directly in your [`next.config.js`](/docs/app/api-reference/next-config-js) file: next.config.js const cspHeader = ` default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; ` module.exports = { async headers() { return [ { source: '/(.*)', headers: [ { key: 'Content-Security-Policy', value: cspHeader.replace(/\n/g, ''), }, ], }, ] }, } [Version History](#version-history) ----------------------------------- We recommend using `v13.4.20+` of Next.js to properly handle and apply nonces. Next Steps ---------- [ App Router ... Routing ### Middleware Learn how to use Middleware to run code before a request is completed. ](/docs/app/building-your-application/routing/middleware)[ App Router ... Functions ### headers API reference for the headers function. ](/docs/app/api-reference/functions/headers) [Previous Draft Mode ](/docs/app/building-your-application/configuring/draft-mode) [Next Testing ](/docs/app/building-your-application/testing) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"6b0d08a342164cd100d65dee472dd33f\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/unstable_cache
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [ unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Parameters](#parameters) * [Returns](#returns) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/unstable_cache.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)unstable\_cache unstable\_cache =============== `unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests. import { getUser } from './data'; import { unstable_cache } from 'next/cache'; const getCachedUser = unstable_cache( async (id) => getUser(id), ['my-app-user'] ); export default async function Component({ userID }) { const user = await getCachedUser(userID); ... } > **Good to know**: Accessing dynamic data sources such as `headers` or `cookies` inside a cache scope is not supported. If you need this data inside a cached function use `headers` outside of the cached function and pass the required dynamic data in as an argument. > **Warning**: This API is unstable and may change in the future. We will provide migration documentation and codemods, if needed, as this API stabilizes. [Parameters](#parameters) ------------------------- const data = unstable_cache(fetchData, keyParts, options)() * `fetchData`: This is an asynchronous function that fetches the data you want to cache. It must be a function that returns a `Promise`. * `keyParts`: This is an array that identifies the cached key. It must contain globally unique values that together identify the key of the data being cached. The cache key also includes the arguments passed to the function. * `options`: This is an object that controls how the cache behaves. It can contain the following properties: * `tags`: An array of tags that can be used to control cache invalidation. * `revalidate`: The number of seconds after which the cache should be revalidated. Omit or pass `false` to cache indefinitely or until matching `revalidateTag()` or `revalidatePath()` methods are called. [Returns](#returns) ------------------- `unstable_cache` returns a function that when invoked, returns a Promise that resolves to the cached data. If the data is not in the cache, the provided function will be invoked, and its result will be cached and returned. [Version History](#version-history) ----------------------------------- Version Changes `v14.0.0` `unstable_cache` introduced. [Previous revalidateTag ](/docs/app/api-reference/functions/revalidateTag) [Next unstable\_noStore ](/docs/app/api-reference/functions/unstable_noStore) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"9bbc9ccb01016523599ce131fcf62828\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [ Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [next/dynamic](#nextdynamic) * [Examples](#examples) * [Skipping SSR](#skipping-ssr) * [Importing Server Components](#importing-server-components) * [Loading External Libraries](#loading-external-libraries) * [Adding a custom loading component](#adding-a-custom-loading-component) * [Importing Named Exports](#importing-named-exports) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/07-lazy-loading.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Lazy Loading Lazy Loading ============ [Lazy loading](https://developer.mozilla.org/docs/Web/Performance/Lazy_loading) in Next.js helps improve the initial loading performance of an application by decreasing the amount of JavaScript needed to render a route. It allows you to defer loading of **Client Components** and imported libraries, and only include them in the client bundle when they're needed. For example, you might want to defer loading a modal until a user clicks to open it. There are two ways you can implement lazy loading in Next.js: 1. Using [Dynamic Imports](#nextdynamic) with `next/dynamic` 2. Using [`React.lazy()`](https://react.dev/reference/react/lazy) with [Suspense](https://react.dev/reference/react/Suspense) By default, Server Components are automatically [code split](https://developer.mozilla.org/docs/Glossary/Code_splitting), and you can use [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) to progressively send pieces of UI from the server to the client. Lazy loading applies to Client Components. [`next/dynamic`](#nextdynamic) ------------------------------ `next/dynamic` is a composite of [`React.lazy()`](https://react.dev/reference/react/lazy) and [Suspense](https://react.dev/reference/react/Suspense). It behaves the same way in the `app` and `pages` directories to allow for incremental migration. [Examples](#examples) --------------------- ### [Importing Client Components](#importing-client-components) app/page.js 'use client' import { useState } from 'react' import dynamic from 'next/dynamic' // Client Components: const ComponentA = dynamic(() => import('../components/A')) const ComponentB = dynamic(() => import('../components/B')) const ComponentC = dynamic(() => import('../components/C'), { ssr: false }) export default function ClientComponentExample() { const [showMore, setShowMore] = useState(false) return ( <div> {/* Load immediately, but in a separate client bundle */} <ComponentA /> {/* Load on demand, only when/if the condition is met */} {showMore && <ComponentB />} <button onClick={() => setShowMore(!showMore)}>Toggle</button> {/* Load only on the client side */} <ComponentC /> </div> ) } ### [Skipping SSR](#skipping-ssr) When using `React.lazy()` and Suspense, Client Components will be pre-rendered (SSR) by default. If you want to disable pre-rendering for a Client Component, you can use the `ssr` option set to `false`: const ComponentC = dynamic(() => import('../components/C'), { ssr: false }) ### [Importing Server Components](#importing-server-components) If you dynamically import a Server Component, only the Client Components that are children of the Server Component will be lazy-loaded - not the Server Component itself. app/page.js import dynamic from 'next/dynamic' // Server Component: const ServerComponent = dynamic(() => import('../components/ServerComponent')) export default function ServerComponentExample() { return ( <div> <ServerComponent /> </div> ) } ### [Loading External Libraries](#loading-external-libraries) External libraries can be loaded on demand using the [`import()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import) function. This example uses the external library `fuse.js` for fuzzy search. The module is only loaded on the client after the user types in the search input. app/page.js 'use client' import { useState } from 'react' const names = ['Tim', 'Joe', 'Bel', 'Lee'] export default function Page() { const [results, setResults] = useState() return ( <div> <input type="text" placeholder="Search" onChange={async (e) => { const { value } = e.currentTarget // Dynamically load fuse.js const Fuse = (await import('fuse.js')).default const fuse = new Fuse(names) setResults(fuse.search(value)) }} /> <pre>Results: {JSON.stringify(results, null, 2)}</pre> </div> ) } ### [Adding a custom loading component](#adding-a-custom-loading-component) app/page.js import dynamic from 'next/dynamic' const WithCustomLoading = dynamic( () => import('../components/WithCustomLoading'), { loading: () => <p>Loading...</p>, } ) export default function Page() { return ( <div> {/* The loading component will be rendered while <WithCustomLoading/> is loading */} <WithCustomLoading /> </div> ) } ### [Importing Named Exports](#importing-named-exports) To dynamically import a named export, you can return it from the Promise returned by [`import()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import) function: components/hello.js 'use client' export function Hello() { return <p>Hello!</p> } app/page.js import dynamic from 'next/dynamic' const ClientComponent = dynamic(() => import('../components/hello').then((mod) => mod.Hello) ) [Previous Bundle Analyzer ](/docs/app/building-your-application/optimizing/bundle-analyzer) [Next Analytics ](/docs/app/building-your-application/optimizing/analytics) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"51c1d32be6860f9f9fb853148e4e2df0\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions/loading
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [ loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/loading.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[File Conventions](/docs/app/api-reference/file-conventions)loading.js loading.js ========== A **loading** file can create instant loading states built on [Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming). By default, this file is a [Server Component](/docs/app/building-your-application/rendering/server-components) - but can also be used as a Client Component through the `"use client"` directive. app/feed/loading.tsx TypeScript JavaScriptTypeScript export default function Loading() { // Or a custom loading skeleton component return <p>Loading...</p> } Loading UI components do not accept any parameters. > **Good to know** > > * While designing loading UI, you may find it helpful to use the [React Developer Tools](https://react.dev/learn/react-developer-tools) to manually toggle Suspense boundaries. [Version History](#version-history) ----------------------------------- Version Changes `v13.0.0` `loading` introduced. [Previous layout.js ](/docs/app/api-reference/file-conventions/layout) [Next middleware.js ](/docs/app/api-reference/file-conventions/middleware) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"81adc876197e078ab449d3b3c5075a65\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/analytics
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [ Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Build Your Own](#build-your-own) * [Web Vitals](#web-vitals) * [Sending results to external systems](#sending-results-to-external-systems) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/08-analytics.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Analytics Analytics ========= Next.js has built-in support for measuring and reporting performance metrics. You can either use the `useReportWebVitals` hook to manage reporting yourself, or alternatively, Vercel provides a [managed service](https://vercel.com/analytics?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) to automatically collect and visualize metrics for you. [Build Your Own](#build-your-own) --------------------------------- app/\_components/web-vitals.js 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { console.log(metric) }) } app/layout.js import { WebVitals } from './_components/web-vitals' export default function Layout({ children }) { return ( <html> <body> <WebVitals /> {children} </body> </html> ) } > Since the `useReportWebVitals` hook requires the `"use client"` directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the `WebVitals` component. View the [API Reference](/docs/app/api-reference/functions/use-report-web-vitals) for more information. [Web Vitals](#web-vitals) ------------------------- [Web Vitals](https://web.dev/vitals/) are a set of useful metrics that aim to capture the user experience of a web page. The following web vitals are all included: * [Time to First Byte](https://developer.mozilla.org/docs/Glossary/Time_to_first_byte) (TTFB) * [First Contentful Paint](https://developer.mozilla.org/docs/Glossary/First_contentful_paint) (FCP) * [Largest Contentful Paint](https://web.dev/lcp/) (LCP) * [First Input Delay](https://web.dev/fid/) (FID) * [Cumulative Layout Shift](https://web.dev/cls/) (CLS) * [Interaction to Next Paint](https://web.dev/inp/) (INP) You can handle all the results of these metrics using the `name` property. app/\_components/web-vitals.tsx TypeScript JavaScriptTypeScript 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { switch (metric.name) { case 'FCP': { // handle FCP results } case 'LCP': { // handle LCP results } // ... } }) } [Sending results to external systems](#sending-results-to-external-systems) --------------------------------------------------------------------------- You can send results to any endpoint to measure and track real user performance on your site. For example: useReportWebVitals((metric) => { const body = JSON.stringify(metric) const url = 'https://example.com/analytics' // Use `navigator.sendBeacon()` if available, falling back to `fetch()`. if (navigator.sendBeacon) { navigator.sendBeacon(url, body) } else { fetch(url, { body, method: 'POST', keepalive: true }) } }) > **Good to know**: If you use [Google Analytics](https://analytics.google.com/analytics/web/), using the `id` value can allow you to construct metric distributions manually (to calculate percentiles, etc.) > useReportWebVitals((metric) => { > // Use `window.gtag` if you initialized Google Analytics as this example: > // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js > window.gtag('event', metric.name, { > value: Math.round( > metric.name === 'CLS' ? metric.value * 1000 : metric.value > ), // values must be integers > event_label: metric.id, // id unique to current page load > non_interaction: true, // avoids affecting bounce rate. > }) > }) > > Read more about [sending results to Google Analytics](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics). [Previous Lazy Loading ](/docs/app/building-your-application/optimizing/lazy-loading) [Next Instrumentation ](/docs/app/building-your-application/optimizing/instrumentation) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"3c3804010e3a5c8f2670de364ab647d9\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/functions/unstable_noStore
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [ unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Usage](#usage) * [Version History](#version-history) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/04-functions/unstable_noStore.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[Functions](/docs/app/api-reference/functions)unstable\_noStore unstable\_noStore ================= `unstable_noStore` can be used to declaratively opt out of static rendering and indicate a particular component should not be cached. import { unstable_noStore as noStore } from 'next/cache'; export default async function Component() { noStore(); const result = await db.query(...); ... } > **Good to know**: > > * `unstable_noStore` is equivalent to `cache: 'no-store'` on a `fetch` > * `unstable_noStore` is preferred over `export const dynamic = 'force-dynamic'` as it is more granular and can be used on a per-component basis * Using `unstable_noStore` inside [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) will not opt out of static generation. Instead, it will defer to the cache configuration to determine whether to cache the result or not. [Usage](#usage) --------------- If you prefer not to pass additional options to `fetch`, like `cache: 'no-store'` or `next: { revalidate: 0 }`, you can use `noStore()` as a replacement for all of these use cases. import { unstable_noStore as noStore } from 'next/cache'; export default async function Component() { noStore(); const result = await db.query(...); ... } [Version History](#version-history) ----------------------------------- Version Changes `v14.0.0` `unstable_noStore` introduced. [Previous unstable\_cache ](/docs/app/api-reference/functions/unstable_cache) [Next useParams ](/docs/app/api-reference/functions/use-params) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"9a55272e23fbeb1064439757ef55cdee\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/routing/internationalization
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [ Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Terminology](#terminology) * [Routing Overview](#routing-overview) * [Localization](#localization) * [Static Generation](#static-generation) * [Resources](#resources) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/01-routing/14-internationalization.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Routing](/docs/app/building-your-application/routing)Internationalization Internationalization ==================== Next.js enables you to configure the routing and rendering of content to support multiple languages. Making your site adaptive to different locales includes translated content (localization) and internationalized routes. [Terminology](#terminology) --------------------------- * **Locale:** An identifier for a set of language and formatting preferences. This usually includes the preferred language of the user and possibly their geographic region. * `en-US`: English as spoken in the United States * `nl-NL`: Dutch as spoken in the Netherlands * `nl`: Dutch, no specific region [Routing Overview](#routing-overview) ------------------------------------- It’s recommended to use the user’s language preferences in the browser to select which locale to use. Changing your preferred language will modify the incoming `Accept-Language` header to your application. For example, using the following libraries, you can look at an incoming `Request` to determine which locale to select, based on the `Headers`, locales you plan to support, and the default locale. middleware.js import { match } from '@formatjs/intl-localematcher' import Negotiator from 'negotiator' let headers = { 'accept-language': 'en-US,en;q=0.5' } let languages = new Negotiator({ headers }).languages() let locales = ['en-US', 'nl-NL', 'nl'] let defaultLocale = 'en-US' match(languages, locales, defaultLocale) // -> 'en-US' Routing can be internationalized by either the sub-path (`/fr/products`) or domain (`my-site.fr/products`). With this information, you can now redirect the user based on the locale inside [Middleware](/docs/app/building-your-application/routing/middleware). middleware.js import { NextResponse } from "next/server"; let locales = ['en-US', 'nl-NL', 'nl'] // Get the preferred locale, similar to the above or using a library function getLocale(request) { ... } export function middleware(request) { // Check if there is any supported locale in the pathname const { pathname } = request.nextUrl const pathnameHasLocale = locales.some( (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` ) if (pathnameHasLocale) return // Redirect if there is no locale const locale = getLocale(request) request.nextUrl.pathname = `/${locale}${pathname}` // e.g. incoming request is /products // The new URL is now /en-US/products return NextResponse.redirect(request.nextUrl) } export const config = { matcher: [ // Skip all internal paths (_next) '/((?!_next).*)', // Optional: only run on root (/) URL // '/' ], } Finally, ensure all special files inside `app/` are nested under `app/[lang]`. This enables the Next.js router to dynamically handle different locales in the route, and forward the `lang` parameter to every layout and page. For example: app/\[lang\]/page.js // You now have access to the current locale // e.g. /en-US/products -> `lang` is "en-US" export default async function Page({ params: { lang } }) { return ... } The root layout can also be nested in the new folder (e.g. `app/[lang]/layout.js`). [Localization](#localization) ----------------------------- Changing displayed content based on the user’s preferred locale, or localization, is not something specific to Next.js. The patterns described below would work the same with any web application. Let’s assume we want to support both English and Dutch content inside our application. We might maintain two different “dictionaries”, which are objects that give us a mapping from some key to a localized string. For example: dictionaries/en.json { "products": { "cart": "Add to Cart" } } dictionaries/nl.json { "products": { "cart": "Toevoegen aan Winkelwagen" } } We can then create a `getDictionary` function to load the translations for the requested locale: app/\[lang\]/dictionaries.js import 'server-only' const dictionaries = { en: () => import('./dictionaries/en.json').then((module) => module.default), nl: () => import('./dictionaries/nl.json').then((module) => module.default), } export const getDictionary = async (locale) => dictionaries[locale]() Given the currently selected language, we can fetch the dictionary inside of a layout or page. app/\[lang\]/page.js import { getDictionary } from './dictionaries' export default async function Page({ params: { lang } }) { const dict = await getDictionary(lang) // en return <button>{dict.products.cart}</button> // Add to Cart } Because all layouts and pages in the `app/` directory default to [Server Components](/docs/app/building-your-application/rendering/server-components), we do not need to worry about the size of the translation files affecting our client-side JavaScript bundle size. This code will **only run on the server**, and only the resulting HTML will be sent to the browser. [Static Generation](#static-generation) --------------------------------------- To generate static routes for a given set of locales, we can use `generateStaticParams` with any page or layout. This can be global, for example, in the root layout: app/\[lang\]/layout.js export async function generateStaticParams() { return [{ lang: 'en-US' }, { lang: 'de' }] } export default function Root({ children, params }) { return ( <html lang={params.lang}> <body>{children}</body> </html> ) } [Resources](#resources) ----------------------- * [Minimal i18n routing and translations](https://github.com/vercel/next.js/tree/canary/examples/app-dir-i18n-routing) * [`next-intl`](https://next-intl-docs.vercel.app/docs/next-13) * [`next-international`](https://github.com/QuiiBz/next-international) * [`next-i18n-router`](https://github.com/i18nexus/next-i18n-router) [Previous Middleware ](/docs/app/building-your-application/routing/middleware) [Next Data Fetching ](/docs/app/building-your-application/data-fetching) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"b9353149d035c11c6d4302be2f0d26fc\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/testing
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Types of tests](#types-of-tests) * [Async Server Components](#async-server-components) * [Guides](#guides) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/08-testing/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Testing Testing ======= In React and Next.js, there are a few different types of tests you can write, each with its own purpose and use cases. This page provides an overview of types and commonly used tools you can use to test your application. [Types of tests](#types-of-tests) --------------------------------- * **Unit testing** involves testing individual units (or blocks of code) in isolation. In React, a unit can be a single function, hook, or component. * **Component testing** is a more focused version of unit testing where the primary subject of the tests is React components. This may involve testing how components are rendered, their interaction with props, and their behavior in response to user events. * **Integration testing** involves testing how multiple units work together. This can be a combination of components, hooks, and functions. * **End-to-End (E2E) Testing** involves testing user flows in an environment that simulates real user scenarios, like the browser. This means testing specific tasks (e.g. signup flow) in a production-like environment. * **Snapshot testing** involves capturing the rendered output of a component and saving it to a snapshot file. When tests run, the current rendered output of the component is compared against the saved snapshot. Changes in the snapshot are used to indicate unexpected changes in behavior. [Async Server Components](#async-server-components) --------------------------------------------------- Since `async` Server Components are new to the React ecosystem, some tools do not fully support them. In the meantime, we recommend using **End-to-End Testing** over **Unit Testing** for `async` components. [Guides](#guides) ----------------- See the guides below to learn how to set up Next.js with these commonly used testing tools: [ ### Vitest Learn how to set up Vitest with Next.js for Unit Testing. ](/docs/app/building-your-application/testing/vitest)[ ### Jest Learn how to set up Jest with Next.js for Unit Testing and Snapshot Testing. ](/docs/app/building-your-application/testing/jest)[ ### Playwright Learn how to set up Playwright with Next.js for End-to-End (E2E) testing. ](/docs/app/building-your-application/testing/playwright)[ ### Cypress Learn how to set up Cypress with Next.js for End-to-End (E2E) and Component Testing. ](/docs/app/building-your-application/testing/cypress) [Previous Content Security Policy ](/docs/app/building-your-application/configuring/content-security-policy) [Next Vitest ](/docs/app/building-your-application/testing/vitest) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"4382f9da40d3020f6d146c6da80d4aac\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/data-fetching
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/02-data-fetching/index.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[Building Your Application](/docs/app/building-your-application)Data Fetching Data Fetching ============= [ ### Fetching, Caching, and Revalidating Learn how to fetch, cache, and revalidate data in your Next.js application. ](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating)[ ### Server Actions and Mutations Learn how to handle form submissions and data mutations with Next.js. ](/docs/app/building-your-application/data-fetching/server-actions-and-mutations)[ ### Data Fetching Patterns and Best Practices Learn about common data fetching patterns in React and Next.js. ](/docs/app/building-your-application/data-fetching/patterns) [Previous Internationalization ](/docs/app/building-your-application/routing/internationalization) [Next Fetching, Caching, and Revalidating ](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"9362a4d3916ed385bb013582c07ac25e\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/testing/vitest
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [ Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Quickstart](#quickstart) * [Manual Setup](#manual-setup) * [Creating your first Vitest Unit Test](#creating-your-first-vitest-unit-test) * [Running your tests](#running-your-tests) * [Additional Resources](#additional-resources) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/08-testing/01-vitest.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Testing](/docs/app/building-your-application/testing)Vitest Setting up Vitest with Next.js ============================== Vite and React Testing Library are frequently used together for **Unit Testing**. This guide will show you how to setup Vitest with Next.js and write your first tests. > **Good to know:** Since `async` Server Components are new to the React ecosystem, Vitest currently does not support them. While you can still run **unit tests** for synchronous Server and Client Components, we recommend using an **E2E tests** for `async` components. [Quickstart](#quickstart) ------------------------- You can use `create-next-app` with the Next.js [with-vitest](https://github.com/vercel/next.js/tree/canary/examples/with-vitest) example to quickly get started: Terminal npx create-next-app@latest --example with-vitest with-vitest-app [Manual Setup](#manual-setup) ----------------------------- To manually set up Vitest, install `vitest` and the following packages as dev dependencies: Terminal npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react # or yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react # or pnpm install -D vitest @vitejs/plugin-react jsdom @testing-library/react # or bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react Create a `vitest.config.ts|js` file in the root of your project, and add the following options: vitest.config.ts TypeScript JavaScriptTypeScript import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], test: { environment: 'jsdom', }, }) For more information on configuring Vitest, please refer to the [Vitest Configuration](https://vitest.dev/config/#configuration) docs. Then, add a `test` script to your `package.json`: package.json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "test": "vitest" } } When you run `npm run test`, Vitest will **watch** for changes in your project by default. [Creating your first Vitest Unit Test](#creating-your-first-vitest-unit-test) ----------------------------------------------------------------------------- Check that everything is working by creating a test to check if the `<Page />` component successfully renders a heading: app/page.tsx TypeScript JavaScriptTypeScript import Link from 'next/link' export default function Page() { return ( <div> <h1>Home</h1> <Link href="/about">About</Link> </div> ) } \_\_tests\_\_/page.test.tsx TypeScript JavaScriptTypeScript import { expect, test } from 'vitest' import { render, screen } from '@testing-library/react' import Page from '../app/page' test('Page', () => { render(<Page />) expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined() }) > **Good to know**: The example above uses the common `__tests__` convention, but test files can also be colocated inside the `app` router. [Running your tests](#running-your-tests) ----------------------------------------- Then, run the following command to run your tests: Terminal npm run test # or yarn test # or pnpm test # or bun test [Additional Resources](#additional-resources) --------------------------------------------- You may find these resources helpful: * [Next.js with Vitest example](https://github.com/vercel/next.js/tree/canary/examples/with-vitest) * [Vitest Docs](https://vitest.dev/guide/) * [React Testing Library Docs](https://testing-library.com/docs/react-testing-library/intro/) [Previous Testing ](/docs/app/building-your-application/testing) [Next Jest ](/docs/app/building-your-application/testing/jest) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"de84bec9a3fdf715615efeaca291ef18\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/api-reference/file-conventions/middleware
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [ middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Exports](#exports) * [Middleware function](#middleware-function) * [Config object (optional)](#config-object-optional) * [Matcher](#matcher) * [Params](#params) * [request](#request) * [NextResponse](#nextresponse) * [Runtime](#runtime) * [Version History](#version-history) * [Learn more about Middleware](#learn-more-about-middleware) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/02-api-reference/02-file-conventions/middleware.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/api-reference)[File Conventions](/docs/app/api-reference/file-conventions)middleware.js middleware.js ============= The `middleware.js|ts` file is used to write [Middleware](/docs/app/building-your-application/routing/middleware) and run code on the server before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly. Middleware executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects. Use the file `middleware.ts` (or .js) in the root of your project to define Middleware. For example, at the same level as `app` or `pages`, or inside `src` if applicable. middleware.ts TypeScript JavaScriptTypeScript import { NextResponse, NextRequest } from 'next/server' // This function can be marked `async` if using `await` inside export function middleware(request: NextRequest) { return NextResponse.redirect(new URL('/home', request.url)) } export const config = { matcher: '/about/:path*', } [Exports](#exports) ------------------- ### [Middleware function](#middleware-function) The file must export a single function, either as a default export or named `middleware`. Note that multiple middleware from the same file are not supported. middleware.js // Example of default export export default function middleware(request) { // Middleware logic } ### [Config object (optional)](#config-object-optional) Optionally, a config object can be exported alongside the Middleware function. This object includes the [matcher](#matcher) to specify paths where the Middleware applies. #### [Matcher](#matcher) The `matcher` option allows you to target specific paths for the Middleware to run on. You can specify these paths in several ways: * For a single path: Directly use a string to define the path, like `'/about'`. * For multiple paths: Use an array to list multiple paths, such as `matcher: ['/about', '/contact']`, which applies the Middleware to both `/about` and `/contact`. Additionally, `matcher` supports complex path specifications through regular expressions, such as `matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)']`, enabling precise control over which paths to include or exclude. The `matcher` option also accepts an array of objects with the following keys: * `source`: The path or pattern used to match the request paths. It can be a string for direct path matching or a pattern for more complex matching. * `regexp` (optional): A regular expression string that fine-tunes the matching based on the source. It provides additional control over which paths are included or excluded. * `locale` (optional): A boolean that, when set to `false`, ignores locale-based routing in path matching. * `has` (optional): Specifies conditions based on the presence of specific request elements such as headers, query parameters, or cookies. * `missing` (optional): Focuses on conditions where certain request elements are absent, like missing headers or cookies. middleware.js export const config = { matcher: [ { source: '/api/*', regexp: '^/api/(.*)', locale: false, has: [ { type: 'header', key: 'Authorization', value: 'Bearer Token' }, { type: 'query', key: 'userId', value: '123' }, ], missing: [{ type: 'cookie', key: 'session', value: 'active' }], }, ], } [Params](#params) ----------------- ### [`request`](#request) When defining Middleware, the default export function accepts a single parameter, `request`. This parameter is an instance of `NextRequest`, which represents the incoming HTTP request. middleware.ts TypeScript JavaScriptTypeScript import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { // Middleware logic goes here } > **Good to know**: > > * `NextRequest` is a type that represents incoming HTTP requests in Next.js Middleware, whereas [`NextResponse`](#nextresponse) is a class used to manipulate and send back HTTP responses. [NextResponse](#nextresponse) ----------------------------- Middleware can use the [`NextResponse`](/docs/app/building-your-application/routing/middleware#nextresponse) object which extends the [Web Response API](https://developer.mozilla.org/en-US/docs/Web/API/Response). By returning a `NextResponse` object, you can directly manipulate cookies, set headers, implement redirects, and rewrite paths. > **Good to know**: For redirects, you can also use `Response.redirect` instead of `NextResponse.redirect`. [Runtime](#runtime) ------------------- Middleware only supports the [Edge runtime](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). The Node.js runtime cannot be used. [Version History](#version-history) ----------------------------------- Version Changes `v13.1.0` Advanced Middleware flags added `v13.0.0` Middleware can modify request headers, response headers, and send responses `v12.2.0` Middleware is stable, please see the [upgrade guide](/docs/messages/middleware-upgrade-guide) `v12.0.9` Enforce absolute URLs in Edge Runtime ([PR](https://github.com/vercel/next.js/pull/33410)) `v12.0.0` Middleware (Beta) added Learn more about Middleware --------------------------- [ App Router ... Routing ### Middleware Learn how to use Middleware to run code before a request is completed. ](/docs/app/building-your-application/routing/middleware) [Previous loading.js ](/docs/app/api-reference/file-conventions/loading) [Next not-found.js ](/docs/app/api-reference/file-conventions/not-found) Was this helpful? supported. Send
{ "contentLength": null, "etag": "W/\"afcf2a4976ea54ea5acb5c9b332238cf\"", "lastModifiedHeader": null, "lastModifiedHtml": null }
https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
Menu Using App Router Features available in /app * [Getting Started](/docs/getting-started) * [Installation](/docs/getting-started/installation) * [Project Structure](/docs/getting-started/project-structure) * [Building Your Application](/docs/app/building-your-application) * [Routing](/docs/app/building-your-application/routing) * [Defining Routes](/docs/app/building-your-application/routing/defining-routes) * [Pages and Layouts](/docs/app/building-your-application/routing/pages-and-layouts) * [Linking and Navigating](/docs/app/building-your-application/routing/linking-and-navigating) * [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) * [Error Handling](/docs/app/building-your-application/routing/error-handling) * [Redirecting](/docs/app/building-your-application/routing/redirecting) * [Route Groups](/docs/app/building-your-application/routing/route-groups) * [Project Organization](/docs/app/building-your-application/routing/colocation) * [Dynamic Routes](/docs/app/building-your-application/routing/dynamic-routes) * [Parallel Routes](/docs/app/building-your-application/routing/parallel-routes) * [Intercepting Routes](/docs/app/building-your-application/routing/intercepting-routes) * [Route Handlers](/docs/app/building-your-application/routing/route-handlers) * [Middleware](/docs/app/building-your-application/routing/middleware) * [Internationalization](/docs/app/building-your-application/routing/internationalization) * [Data Fetching](/docs/app/building-your-application/data-fetching) * [Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) * [Server Actions and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) * [Data Fetching Patterns and Best Practices](/docs/app/building-your-application/data-fetching/patterns) * [Rendering](/docs/app/building-your-application/rendering) * [Server Components](/docs/app/building-your-application/rendering/server-components) * [Client Components](/docs/app/building-your-application/rendering/client-components) * [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) * [Edge and Node.js Runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) * [Caching](/docs/app/building-your-application/caching) * [Styling](/docs/app/building-your-application/styling) * [CSS Modules](/docs/app/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/app/building-your-application/styling/css-in-js) * [Sass](/docs/app/building-your-application/styling/sass) * [Optimizing](/docs/app/building-your-application/optimizing) * [Images](/docs/app/building-your-application/optimizing/images) * [Videos](/docs/app/building-your-application/optimizing/videos) * [Fonts](/docs/app/building-your-application/optimizing/fonts) * [Metadata](/docs/app/building-your-application/optimizing/metadata) * [Scripts](/docs/app/building-your-application/optimizing/scripts) * [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) * [Lazy Loading](/docs/app/building-your-application/optimizing/lazy-loading) * [Analytics](/docs/app/building-your-application/optimizing/analytics) * [ Instrumentation](/docs/app/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/app/building-your-application/optimizing/open-telemetry) * [Static Assets](/docs/app/building-your-application/optimizing/static-assets) * [Third Party Libraries](/docs/app/building-your-application/optimizing/third-party-libraries) * [Memory Usage](/docs/app/building-your-application/optimizing/memory-usage) * [Configuring](/docs/app/building-your-application/configuring) * [TypeScript](/docs/app/building-your-application/configuring/typescript) * [ESLint](/docs/app/building-your-application/configuring/eslint) * [Environment Variables](/docs/app/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) * [MDX](/docs/app/building-your-application/configuring/mdx) * [src Directory](/docs/app/building-your-application/configuring/src-directory) * [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) * [Content Security Policy](/docs/app/building-your-application/configuring/content-security-policy) * [Testing](/docs/app/building-your-application/testing) * [Vitest](/docs/app/building-your-application/testing/vitest) * [Jest](/docs/app/building-your-application/testing/jest) * [Playwright](/docs/app/building-your-application/testing/playwright) * [Cypress](/docs/app/building-your-application/testing/cypress) * [Authentication](/docs/app/building-your-application/authentication) * [Deploying](/docs/app/building-your-application/deploying) * [Production Checklist](/docs/app/building-your-application/deploying/production-checklist) * [Static Exports](/docs/app/building-your-application/deploying/static-exports) * [Upgrading](/docs/app/building-your-application/upgrading) * [Codemods](/docs/app/building-your-application/upgrading/codemods) * [App Router Migration](/docs/app/building-your-application/upgrading/app-router-migration) * [Version 14](/docs/app/building-your-application/upgrading/version-14) * [Migrating from Vite](/docs/app/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/app/building-your-application/upgrading/from-create-react-app) * [API Reference](/docs/app/api-reference) * [Components](/docs/app/api-reference/components) * [Font](/docs/app/api-reference/components/font) * [<Image>](/docs/app/api-reference/components/image) * [<Link>](/docs/app/api-reference/components/link) * [<Script>](/docs/app/api-reference/components/script) * [File Conventions](/docs/app/api-reference/file-conventions) * [default.js](/docs/app/api-reference/file-conventions/default) * [error.js](/docs/app/api-reference/file-conventions/error) * [instrumentation.js](/docs/app/api-reference/file-conventions/instrumentation) * [layout.js](/docs/app/api-reference/file-conventions/layout) * [loading.js](/docs/app/api-reference/file-conventions/loading) * [middleware.js](/docs/app/api-reference/file-conventions/middleware) * [not-found.js](/docs/app/api-reference/file-conventions/not-found) * [page.js](/docs/app/api-reference/file-conventions/page) * [route.js](/docs/app/api-reference/file-conventions/route) * [Route Segment Config](/docs/app/api-reference/file-conventions/route-segment-config) * [template.js](/docs/app/api-reference/file-conventions/template) * [Metadata Files](/docs/app/api-reference/file-conventions/metadata) * [favicon, icon, and apple-icon](/docs/app/api-reference/file-conventions/metadata/app-icons) * [manifest.json](/docs/app/api-reference/file-conventions/metadata/manifest) * [opengraph-image and twitter-image](/docs/app/api-reference/file-conventions/metadata/opengraph-image) * [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots) * [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap) * [Functions](/docs/app/api-reference/functions) * [cookies](/docs/app/api-reference/functions/cookies) * [draftMode](/docs/app/api-reference/functions/draft-mode) * [fetch](/docs/app/api-reference/functions/fetch) * [generateImageMetadata](/docs/app/api-reference/functions/generate-image-metadata) * [generateMetadata](/docs/app/api-reference/functions/generate-metadata) * [generateSitemaps](/docs/app/api-reference/functions/generate-sitemaps) * [generateStaticParams](/docs/app/api-reference/functions/generate-static-params) * [generateViewport](/docs/app/api-reference/functions/generate-viewport) * [headers](/docs/app/api-reference/functions/headers) * [ImageResponse](/docs/app/api-reference/functions/image-response) * [NextRequest](/docs/app/api-reference/functions/next-request) * [NextResponse](/docs/app/api-reference/functions/next-response) * [notFound](/docs/app/api-reference/functions/not-found) * [permanentRedirect](/docs/app/api-reference/functions/permanentRedirect) * [redirect](/docs/app/api-reference/functions/redirect) * [revalidatePath](/docs/app/api-reference/functions/revalidatePath) * [revalidateTag](/docs/app/api-reference/functions/revalidateTag) * [unstable\_cache](/docs/app/api-reference/functions/unstable_cache) * [unstable\_noStore](/docs/app/api-reference/functions/unstable_noStore) * [useParams](/docs/app/api-reference/functions/use-params) * [usePathname](/docs/app/api-reference/functions/use-pathname) * [useReportWebVitals](/docs/app/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/app/api-reference/functions/use-router) * [useSearchParams](/docs/app/api-reference/functions/use-search-params) * [useSelectedLayoutSegment](/docs/app/api-reference/functions/use-selected-layout-segment) * [useSelectedLayoutSegments](/docs/app/api-reference/functions/use-selected-layout-segments) * [userAgent](/docs/app/api-reference/functions/userAgent) * [next.config.js Options](/docs/app/api-reference/next-config-js) * [appDir](/docs/app/api-reference/next-config-js/appDir) * [assetPrefix](/docs/app/api-reference/next-config-js/assetPrefix) * [basePath](/docs/app/api-reference/next-config-js/basePath) * [compress](/docs/app/api-reference/next-config-js/compress) * [crossOrigin](/docs/app/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/app/api-reference/next-config-js/devIndicators) * [distDir](/docs/app/api-reference/next-config-js/distDir) * [env](/docs/app/api-reference/next-config-js/env) * [eslint](/docs/app/api-reference/next-config-js/eslint) * [exportPathMap](/docs/app/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/app/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/app/api-reference/next-config-js/generateEtags) * [headers](/docs/app/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/app/api-reference/next-config-js/httpAgentOptions) * [images](/docs/app/api-reference/next-config-js/images) * [cacheHandler](/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath) * [instrumentationHook](/docs/app/api-reference/next-config-js/instrumentationHook) * [logging](/docs/app/api-reference/next-config-js/logging) * [mdxRs](/docs/app/api-reference/next-config-js/mdxRs) * [onDemandEntries](/docs/app/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/app/api-reference/next-config-js/optimizePackageImports) * [output](/docs/app/api-reference/next-config-js/output) * [pageExtensions](/docs/app/api-reference/next-config-js/pageExtensions) * [Partial Prerendering (experimental)](/docs/app/api-reference/next-config-js/partial-prerendering) * [poweredByHeader](/docs/app/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/app/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/app/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/app/api-reference/next-config-js/redirects) * [rewrites](/docs/app/api-reference/next-config-js/rewrites) * [serverActions](/docs/app/api-reference/next-config-js/serverActions) * [serverComponentsExternalPackages](/docs/app/api-reference/next-config-js/serverComponentsExternalPackages) * [StaleTimes (experimental)](/docs/app/api-reference/next-config-js/staleTimes) * [trailingSlash](/docs/app/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/app/api-reference/next-config-js/transpilePackages) * [turbo](/docs/app/api-reference/next-config-js/turbo) * [typedRoutes](/docs/app/api-reference/next-config-js/typedRoutes) * [typescript](/docs/app/api-reference/next-config-js/typescript) * [urlImports](/docs/app/api-reference/next-config-js/urlImports) * [webpack](/docs/app/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/app/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/app/api-reference/create-next-app) * [Edge Runtime](/docs/app/api-reference/edge) * [Next.js CLI](/docs/app/api-reference/next-cli) * [Building Your Application](/docs/pages/building-your-application) * [Routing](/docs/pages/building-your-application/routing) * [Pages and Layouts](/docs/pages/building-your-application/routing/pages-and-layouts) * [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes) * [Linking and Navigating](/docs/pages/building-your-application/routing/linking-and-navigating) * [Redirecting](/docs/pages/building-your-application/routing/redirecting) * [Custom App](/docs/pages/building-your-application/routing/custom-app) * [Custom Document](/docs/pages/building-your-application/routing/custom-document) * [API Routes](/docs/pages/building-your-application/routing/api-routes) * [Custom Errors](/docs/pages/building-your-application/routing/custom-error) * [Internationalization](/docs/pages/building-your-application/routing/internationalization) * [Middleware](/docs/pages/building-your-application/routing/middleware) * [Rendering](/docs/pages/building-your-application/rendering) * [Server-side Rendering (SSR)](/docs/pages/building-your-application/rendering/server-side-rendering) * [Static Site Generation (SSG)](/docs/pages/building-your-application/rendering/static-site-generation) * [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) * [Client-side Rendering (CSR)](/docs/pages/building-your-application/rendering/client-side-rendering) * [Edge and Node.js Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes) * [Data Fetching](/docs/pages/building-your-application/data-fetching) * [getStaticProps](/docs/pages/building-your-application/data-fetching/get-static-props) * [getStaticPaths](/docs/pages/building-your-application/data-fetching/get-static-paths) * [Forms and Mutations](/docs/pages/building-your-application/data-fetching/forms-and-mutations) * [getServerSideProps](/docs/pages/building-your-application/data-fetching/get-server-side-props) * [Incremental Static Regeneration (ISR)](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) * [Client-side Fetching](/docs/pages/building-your-application/data-fetching/client-side) * [Styling](/docs/pages/building-your-application/styling) * [CSS Modules](/docs/pages/building-your-application/styling/css-modules) * [Tailwind CSS](/docs/pages/building-your-application/styling/tailwind-css) * [CSS-in-JS](/docs/pages/building-your-application/styling/css-in-js) * [Sass](/docs/pages/building-your-application/styling/sass) * [Optimizing](/docs/pages/building-your-application/optimizing) * [Images](/docs/pages/building-your-application/optimizing/images) * [Fonts](/docs/pages/building-your-application/optimizing/fonts) * [Scripts](/docs/pages/building-your-application/optimizing/scripts) * [Static Assets](/docs/pages/building-your-application/optimizing/static-assets) * [Bundle Analyzer](/docs/pages/building-your-application/optimizing/bundle-analyzer) * [Analytics](/docs/pages/building-your-application/optimizing/analytics) * [Lazy Loading](/docs/pages/building-your-application/optimizing/lazy-loading) * [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) * [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry) * [Third Party Libraries](/docs/pages/building-your-application/optimizing/third-party-libraries) * [Configuring](/docs/pages/building-your-application/configuring) * [TypeScript](/docs/pages/building-your-application/configuring/typescript) * [ESLint](/docs/pages/building-your-application/configuring/eslint) * [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) * [Absolute Imports and Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases) * [src Directory](/docs/pages/building-your-application/configuring/src-directory) * [MDX](/docs/pages/building-your-application/configuring/mdx) * [AMP](/docs/pages/building-your-application/configuring/amp) * [Babel](/docs/pages/building-your-application/configuring/babel) * [PostCSS](/docs/pages/building-your-application/configuring/post-css) * [Custom Server](/docs/pages/building-your-application/configuring/custom-server) * [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) * [Error Handling](/docs/pages/building-your-application/configuring/error-handling) * [Debugging](/docs/pages/building-your-application/configuring/debugging) * [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) * [Content Security Policy](/docs/pages/building-your-application/configuring/content-security-policy) * [Testing](/docs/pages/building-your-application/testing) * [Vitest](/docs/pages/building-your-application/testing/vitest) * [Jest](/docs/pages/building-your-application/testing/jest) * [Playwright](/docs/pages/building-your-application/testing/playwright) * [Cypress](/docs/pages/building-your-application/testing/cypress) * [Authentication](/docs/pages/building-your-application/authentication) * [Deploying](/docs/pages/building-your-application/deploying) * [Production Checklist](/docs/pages/building-your-application/deploying/production-checklist) * [Static Exports](/docs/pages/building-your-application/deploying/static-exports) * [Multi Zones](/docs/pages/building-your-application/deploying/multi-zones) * [Continuous Integration (CI) Build Caching](/docs/pages/building-your-application/deploying/ci-build-caching) * [Upgrading](/docs/pages/building-your-application/upgrading) * [Codemods](/docs/pages/building-your-application/upgrading/codemods) * [From Pages to App](/docs/pages/building-your-application/upgrading/app-router-migration) * [Migrating from Vite](/docs/pages/building-your-application/upgrading/from-vite) * [Migrating from Create React App](/docs/pages/building-your-application/upgrading/from-create-react-app) * [Version 14](/docs/pages/building-your-application/upgrading/version-14) * [Version 13](/docs/pages/building-your-application/upgrading/version-13) * [Version 12](/docs/pages/building-your-application/upgrading/version-12) * [Version 11](/docs/pages/building-your-application/upgrading/version-11) * [Version 10](/docs/pages/building-your-application/upgrading/version-10) * [Version 9](/docs/pages/building-your-application/upgrading/version-9) * [API Reference](/docs/pages/api-reference) * [Components](/docs/pages/api-reference/components) * [Font](/docs/pages/api-reference/components/font) * [<Head>](/docs/pages/api-reference/components/head) * [<Image>](/docs/pages/api-reference/components/image) * [<Image> (Legacy)](/docs/pages/api-reference/components/image-legacy) * [<Link>](/docs/pages/api-reference/components/link) * [<Script>](/docs/pages/api-reference/components/script) * [Functions](/docs/pages/api-reference/functions) * [getInitialProps](/docs/pages/api-reference/functions/get-initial-props) * [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props) * [getStaticPaths](/docs/pages/api-reference/functions/get-static-paths) * [getStaticProps](/docs/pages/api-reference/functions/get-static-props) * [NextRequest](/docs/pages/api-reference/functions/next-request) * [NextResponse](/docs/pages/api-reference/functions/next-response) * [useAmp](/docs/pages/api-reference/functions/use-amp) * [useReportWebVitals](/docs/pages/api-reference/functions/use-report-web-vitals) * [useRouter](/docs/pages/api-reference/functions/use-router) * [userAgent](/docs/pages/api-reference/functions/userAgent) * [next.config.js Options](/docs/pages/api-reference/next-config-js) * [assetPrefix](/docs/pages/api-reference/next-config-js/assetPrefix) * [basePath](/docs/pages/api-reference/next-config-js/basePath) * [compress](/docs/pages/api-reference/next-config-js/compress) * [crossOrigin](/docs/pages/api-reference/next-config-js/crossOrigin) * [devIndicators](/docs/pages/api-reference/next-config-js/devIndicators) * [distDir](/docs/pages/api-reference/next-config-js/distDir) * [env](/docs/pages/api-reference/next-config-js/env) * [eslint](/docs/pages/api-reference/next-config-js/eslint) * [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) * [generateBuildId](/docs/pages/api-reference/next-config-js/generateBuildId) * [generateEtags](/docs/pages/api-reference/next-config-js/generateEtags) * [headers](/docs/pages/api-reference/next-config-js/headers) * [httpAgentOptions](/docs/pages/api-reference/next-config-js/httpAgentOptions) * [images](/docs/pages/api-reference/next-config-js/images) * [instrumentationHook](/docs/pages/api-reference/next-config-js/instrumentationHook) * [onDemandEntries](/docs/pages/api-reference/next-config-js/onDemandEntries) * [optimizePackageImports](/docs/pages/api-reference/next-config-js/optimizePackageImports) * [output](/docs/pages/api-reference/next-config-js/output) * [pageExtensions](/docs/pages/api-reference/next-config-js/pageExtensions) * [poweredByHeader](/docs/pages/api-reference/next-config-js/poweredByHeader) * [productionBrowserSourceMaps](/docs/pages/api-reference/next-config-js/productionBrowserSourceMaps) * [reactStrictMode](/docs/pages/api-reference/next-config-js/reactStrictMode) * [redirects](/docs/pages/api-reference/next-config-js/redirects) * [rewrites](/docs/pages/api-reference/next-config-js/rewrites) * [Runtime Config](/docs/pages/api-reference/next-config-js/runtime-configuration) * [trailingSlash](/docs/pages/api-reference/next-config-js/trailingSlash) * [transpilePackages](/docs/pages/api-reference/next-config-js/transpilePackages) * [turbo](/docs/pages/api-reference/next-config-js/turbo) * [typescript](/docs/pages/api-reference/next-config-js/typescript) * [urlImports](/docs/pages/api-reference/next-config-js/urlImports) * [webpack](/docs/pages/api-reference/next-config-js/webpack) * [webVitalsAttribution](/docs/pages/api-reference/next-config-js/webVitalsAttribution) * [create-next-app](/docs/pages/api-reference/create-next-app) * [Next.js CLI](/docs/pages/api-reference/next-cli) * [Edge Runtime](/docs/pages/api-reference/edge) * [Architecture](/docs/architecture) * [Accessibility](/docs/architecture/accessibility) * [Fast Refresh](/docs/architecture/fast-refresh) * [Next.js Compiler](/docs/architecture/nextjs-compiler) * [Supported Browsers](/docs/architecture/supported-browsers) * [Turbopack](/docs/architecture/turbopack) * [Community](/docs/community) * [Contribution Guide](/docs/community/contribution-guide) On this page * [Convention](#convention) * [Examples](#examples) * [Importing files with side effects](#importing-files-with-side-effects) * [Importing runtime-specific code](#importing-runtime-specific-code) * [Learn more about Instrumentation](#learn-more-about-instrumentation) [Edit this page on GitHub](https://github.com/vercel/next.js/edit/canary/docs/02-app/01-building-your-application/06-optimizing/09-instrumentation.mdx) [Managed Next.js (Vercel)](https://vercel.com/solutions/nextjs?utm_source=next_site&utm_medium=web&utm_campaign=managed_nextjs_solutions_page) Scroll to top [App Router](/docs/app)[...](/docs/app/building-your-application)[Optimizing](/docs/app/building-your-application/optimizing)Instrumentation Instrumentation =============== Instrumentation is the process of using code to integrate monitoring and logging tools into your application. This allows you to track the performance and behavior of your application, and to debug issues in production. [Convention](#convention) ------------------------- To set up instrumentation, create `instrumentation.ts|js` file in the **root directory** of your project (or inside the [`src`](/docs/app/building-your-application/configuring/src-directory) folder if using one). Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated. For example, to use Next.js with [OpenTelemetry](https://opentelemetry.io/) and [@vercel/otel](https://vercel.com/docs/observability/otel-overview): instrumentation.ts TypeScript JavaScriptTypeScript import { registerOTel } from '@vercel/otel' export function register() { registerOTel('next-app') } See the [Next.js with OpenTelemetry example](https://github.com/vercel/next.js/tree/canary/examples/with-opentelemetry) for a complete implementation. > **Good to know** > > * This feature is **experimental**. To use it, you must explicitly opt in by defining [`experimental.instrumentationHook = true;`](/docs/app/api-reference/next-config-js/instrumentationHook) in your `next.config.js`. > * The `instrumentation` file should be in the root of your project and not inside the `app` or `pages` directory. If you're using the `src` folder, then place the file inside `src` alongside `pages` and `app`. > * If you use the [`pageExtensions` config option](/docs/app/api-reference/next-config-js/pageExtensions) to add a suffix, you will also need to update the `instrumentation` filename to match. [Examples](#examples) --------------------- ### [Importing files with side effects](#importing-files-with-side-effects) Sometimes, it may be useful to import a file in your code because of the side effects it will cause. For example, you might import a file that defines a set of global variables, but never explicitly use the imported file in your code. You would still have access to the global variables the package has declared. We recommend importing files using JavaScript `import` syntax within your `register` function. The following example demonstrates a basic usage of `import` in a `register` function: instrumentation.ts TypeScript JavaScriptTypeScript export async function register() { await import('package-with-side-effect') } > **Good to know:** > > We recommend importing the file from within the `register` function, rather than at the top of the file. By doing this, you can colocate all of your side effects in one place in your code, and avoid any unintended consequences from importing globally at the top of the file. ### [Importing runtime-specific code](#importing-runtime-specific-code) Next.js calls `register` in all environments, so it's important to conditionally import any code that doesn't support specific runtimes (e.g. [Edge](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#edge-runtime) or [Node.js](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#nodejs-runtime)). You can use the `NEXT_RUNTIME` environment variable to get the current environment: instrumentation.ts TypeScript JavaScriptTypeScript export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { await import('./instrumentation-node') } if (process.env.NEXT_RUNTIME === 'edge') { await import('./instrumentation-edge') } } Learn more about Instrumentation -------------------------------- [ App Router ... File Conventions ### instrumentation.js API reference for the instrumentation.js file. ](/docs/app/api-reference/file-conventions/instrumentation)[ App Router ... next.config.js Options ### instrumentationHook Use the instrumentationHook option to set up instrumentation in your Next.js App. ](/docs/app/api-reference/next-config-js/instrumentationHook) [Previous Analytics ](/docs/app/building-your-application/optimizing/analytics) [Next OpenTelemetry ](/docs/app/building-your-application/optimizing/open-telemetry) Was this helpful? supported. Send