### Function-Based Configuration in next.config.mjs Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/index.mdx Next.js configuration using a function pattern that receives phase and defaultConfig parameters. Allows dynamic configuration based on build phase and enables access to default Next.js configuration. ```javascript // @ts-check export default (phase, { defaultConfig }) => { /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } return nextConfig } ``` -------------------------------- ### Phase-Based Configuration with next/constants Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/index.mdx Phase-aware Next.js configuration that applies different settings based on the current build phase. Imports phase constants from 'next/constants' and conditionally returns configuration options for development server or production builds. ```javascript // @ts-check const { PHASE_DEVELOPMENT_SERVER } = require('next/constants') module.exports = (phase, { defaultConfig }) => { if (phase === PHASE_DEVELOPMENT_SERVER) { return { /* development only config options here */ } } return { /* config options for all phases except development here */ } } ``` -------------------------------- ### Configure basePath in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/basePath.mdx Set the basePath configuration option in next.config.js to define a path prefix for the application. This value must be configured at build time and is inlined into client-side bundles, so it cannot be changed without rebuilding. ```javascript module.exports = { basePath: '/docs', } ``` -------------------------------- ### Basic next.config.js Setup with CommonJS Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/index.mdx Standard Next.js configuration file setup using CommonJS module format. This is the default configuration file placed in the project root directory. The file exports a NextConfig object that contains all application configuration options. ```javascript // @ts-check /** @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } module.exports = nextConfig ``` -------------------------------- ### TypeScript Configuration with next.config.ts Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/index.mdx Next.js configuration using TypeScript syntax with .ts extension. Provides full type safety with NextConfig type import from 'next' package. Ideal for TypeScript projects requiring type-checked configuration. ```typescript import type { NextConfig } from 'next' const nextConfig: NextConfig = { /* config options here */ } export default nextConfig ``` -------------------------------- ### Configure TypeScript Options in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/typescript.mdx Set up TypeScript behavior in Next.js by configuring the typescript object in next.config.js. This example shows the default configuration with ignoreBuildErrors set to false and tsconfigPath pointing to the standard tsconfig.json file. Both options control error handling during production builds and custom configuration file paths. ```javascript module.exports = { typescript: { ignoreBuildErrors: false, tsconfigPath: 'tsconfig.json', }, } ``` -------------------------------- ### Specify Custom TypeScript Configuration File Path Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/typescript.mdx Configure Next.js to use a custom TypeScript configuration file for builds and tooling instead of the default tsconfig.json. This allows you to maintain separate TypeScript configurations for different build scenarios, such as using tsconfig.build.json for production builds. ```javascript module.exports = { typescript: { tsconfigPath: 'tsconfig.build.json', }, } ``` -------------------------------- ### Async Configuration Function in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/index.mdx Asynchronous Next.js configuration function supported since version 12.1.0. Enables async operations during configuration loading, useful for fetching configuration from external sources. Returns a NextConfig object. ```javascript // @ts-check module.exports = async (phase, { defaultConfig }) => { /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } return nextConfig } ``` -------------------------------- ### Set custom pageExtensions in Next.js configuration Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/pageExtensions.mdx Configures Next.js to recognize custom file extensions for pages in the Pages Router. This configuration affects all pages including _app.js, _document.js, proxy.js, instrumentation.js, and pages in the api directory. Renaming pages to match the configured extensions is required after changing this setting. ```javascript module.exports = { pageExtensions: ['mdx', 'md', 'jsx', 'js', 'tsx', 'ts'], } ``` -------------------------------- ### ECMAScript Modules Configuration with next.config.mjs Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/index.mdx Next.js configuration using ECMAScript modules syntax with .mjs extension. Enables modern ES module syntax including import/export statements instead of CommonJS require/module.exports. ```javascript // @ts-check /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } export default nextConfig ``` -------------------------------- ### Configure cacheHandlers in Next.js config Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/cacheHandlers.mdx Set up custom cache handlers in your Next.js configuration file by referencing separate handler files. The configuration supports both TypeScript and JavaScript formats and allows you to specify handlers for default and remote cache strategies. ```typescript import type { NextConfig } from 'next' const nextConfig: NextConfig = { cacheHandlers: { default: require.resolve('./cache-handlers/default-handler.js'), remote: require.resolve('./cache-handlers/remote-handler.js'), }, } export default nextConfig ``` ```javascript module.exports = { cacheHandlers: { default: require.resolve('./cache-handlers/default-handler.js'), remote: require.resolve('./cache-handlers/remote-handler.js'), }, } ``` -------------------------------- ### Configure allowedDevOrigins in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/allowedDevOrigins.mdx Set up the allowedDevOrigins configuration in your Next.js project to allow requests from additional origins during development. This option accepts an array of origin strings and supports wildcard patterns for flexible domain matching. ```javascript module.exports = { allowedDevOrigins: ['local-origin.dev', '*.local-origin.dev'], } ``` -------------------------------- ### Akamai Image Loader Configuration Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/images.mdx Configures a custom loader for Akamai's Image and Video Manager service using the imwidth parameter to specify image width for optimization. ```javascript // Docs: https://techdocs.akamai.com/ivm/reference/test-images-on-demand export default function akamaiLoader({ src, width, quality }) { return `https://example.com/${src}?imwidth=${width}` } ``` -------------------------------- ### Cloudinary Image Loader Configuration Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/images.mdx Configures a custom loader for Cloudinary's image transformation service using comma-separated transformation parameters including format, constraint, width, and quality. ```javascript // Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg export default function cloudinaryLoader({ src, width, quality }) { const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`] return `https://example.com/${params.join(',')}${src}` } ``` -------------------------------- ### Configure CSP with Subresource Integrity in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/content-security-policy.mdx Combines CSP configuration with experimental SRI support in Next.js. This setup enables static generation with strict CSP policies by using hash-based integrity verification instead of nonces. The configuration allows CDN caching while maintaining security through build-time generated hashes for JavaScript assets. ```javascript const cspHeader = ` default-src 'self'; script-src 'self'; style-src 'self'; 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 = { experimental: { sri: { algorithm: 'sha256', }, }, async headers() { return [ { source: '/(.*)', headers: [ { key: 'Content-Security-Policy', value: cspHeader.replace(/\n/g, ''), }, ], }, ] }, } ``` -------------------------------- ### Customize Next.js Babel presets with specific options in .babelrc Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/02-guides/babel.mdx This `.babelrc` configuration shows how to pass custom options to the `next/babel` preset itself, which then allows configuring its internal presets like `preset-env`, `transform-runtime`, `styled-jsx`, and `class-properties`. This enables fine-grained control over how Babel transpiles code within a Next.js application by defining configuration objects for each sub-preset. ```json { "presets": [ [ "next/babel", { "preset-env": {}, "transform-runtime": {}, "styled-jsx": {}, "class-properties": {} } ] ], "plugins": [] } ``` -------------------------------- ### Configure Next.js headers with basePath support Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/headers.mdx This Next.js configuration example demonstrates how to define custom headers with `basePath` integration. It shows how `source` paths are automatically prefixed by the configured `basePath` and how to explicitly disable this behavior for specific headers using `basePath: false` within the header object. ```javascript module.exports = { basePath: '/docs', async headers() { return [ { source: '/with-basePath', // becomes /docs/with-basePath headers: [ { key: 'x-hello', value: 'world', }, ], }, { source: '/without-basePath', // is not modified since basePath: false is set headers: [ { key: 'x-hello', value: 'world', }, ], basePath: false, }, ] }, } ``` -------------------------------- ### Configure Next.js headers with i18n support Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/headers.mdx This Next.js configuration example illustrates how to define custom headers with `i18n` integration. It demonstrates automatic locale prefixing for `source` paths based on configured `locales` and how to disable this for specific headers using `locale: false`, which then requires manual locale prefixes in the `source`. ```javascript module.exports = { i18n: { locales: ['en', 'fr', 'de'], defaultLocale: 'en', }, async headers() { return [ { source: '/with-locale', // automatically handles all locales headers: [ { key: 'x-hello', value: 'world', }, ], }, { // does not handle locales automatically since locale: false is set source: '/nl/with-locale-manual', locale: false, headers: [ { key: 'x-hello', value: 'world', }, ], }, { // this matches '/' since `en` is the defaultLocale source: '/en', locale: false, headers: [ { key: 'x-hello', value: 'world', }, ], }, { // this gets converted to /(en|fr|de)/(.*) so will not match the top-level // `/` or `/fr` routes like /:path* would source: '/(.*)', headers: [ { key: 'x-hello', value: 'world', }, ], }, ] }, } ``` -------------------------------- ### Configure Cypress for E2E Testing Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/testing/cypress.mdx These code snippets demonstrate how to configure Cypress for End-to-End (E2E) testing using `cypress.config.ts` or `cypress.config.js`. The `defineConfig` helper from Cypress ensures proper configuration, specifically setting up the `e2e` property for test-related settings. ```typescript import { defineConfig } from 'cypress' export default defineConfig({ e2e: { setupNodeEvents(on, config) {}, }, }) ``` ```javascript const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) {}, }, }) ``` -------------------------------- ### Configure cacheHandlers in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/cacheHandlers.mdx Learn how to define custom cache handler paths in your Next.js configuration file to control cache storage and sharing for 'use cache' directives. ```APIDOC ## Configure cacheHandlers in next.config.js ### Description The `cacheHandlers` configuration in `next.config.js` allows you to specify custom cache storage implementations for `'use cache'` and `'use cache: remote'` directives. This enables the use of external services or custom logic for caching components and functions. ### Method Configuration (File-based) ### Endpoint N/A (Configuration, not an HTTP endpoint) ### Parameters #### Configuration Properties - **cacheHandlers** (object) - Required - An object defining custom cache handlers. - **default** (string) - Optional - Path to the module implementing the `CacheHandler` interface for the `'use cache'` directive. Uses an in-memory LRU cache if not configured. - **remote** (string) - Optional - Path to the module implementing the `CacheHandler` interface for the `'use cache: remote'` directive. Uses an in-memory LRU cache if not configured. - **[additional_name]** (string) - Optional - Path to the module for additional named handlers (e.g., `'use cache: '`). #### Request Body N/A (This is a configuration file, not an API request body) ### Request Example ```ts // next.config.ts import type { NextConfig } from 'next' const nextConfig: NextConfig = { cacheHandlers: { default: require.resolve('./cache-handlers/default-handler.js'), remote: require.resolve('./cache-handlers/remote-handler.js'), }, } export default nextConfig ``` ```js // next.config.js module.exports = { cacheHandlers: { default: require.resolve('./cache-handlers/default-handler.js'), remote: require.resolve('./cache-handlers/remote-handler.js'), }, } ``` ### Response N/A (Configuration does not have a direct API response) ``` -------------------------------- ### Configure htmlLimitedBots with Custom Bot Pattern Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/htmlLimitedBots.mdx Set up custom user agent patterns in Next.js configuration to receive blocking metadata. This example demonstrates specifying multiple bot identifiers using a regex pattern. The configuration can be defined in either TypeScript or JavaScript config files and will override Next.js' default bot list. ```typescript import type { NextConfig } from 'next' const config: NextConfig = { htmlLimitedBots: /MySpecialBot|MyAnotherSpecialBot|SimpleCrawler/, } export default config ``` ```javascript module.exports = { htmlLimitedBots: /MySpecialBot|MyAnotherSpecialBot|SimpleCrawler/, } ``` -------------------------------- ### Create Next.js configuration file Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/migrating/from-vite.mdx Create a next.config.mjs file at the project root to configure Next.js options. This configuration sets up Single-Page Application (SPA) output mode and specifies the build directory as ./dist/. The file supports both .js and .mjs extensions. ```javascript /** @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 ``` -------------------------------- ### Configure basic Next.js Babel setup in .babelrc Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/02-guides/babel.mdx This configuration file (`.babelrc`) initializes Babel for a Next.js project. It includes the `next/babel` preset to ensure compatibility with Next.js's compilation requirements for React applications and server-side code. The `plugins` array is initially empty but can be extended with additional plugins. ```json { "presets": ["next/babel"], "plugins": [] } ``` -------------------------------- ### Configure Route Segment Options in Next.js Route Handler Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/route.mdx Export segment configuration constants to control caching, dynamic behavior, and runtime environment for Route Handlers. Options include dynamic rendering mode, parameter handling, revalidation strategy, fetch caching, runtime selection, and preferred region. These settings apply the same route segment configuration used for pages and layouts. ```typescript export const dynamic = 'auto' export const dynamicParams = true export const revalidate = false export const fetchCache = 'auto' export const runtime = 'nodejs' export const preferredRegion = 'auto' ``` ```javascript export const dynamic = 'auto' export const dynamicParams = true export const revalidate = false export const fetchCache = 'auto' export const runtime = 'nodejs' export const preferredRegion = 'auto' ``` -------------------------------- ### Configure Custom Image Loader and Path Prefix in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/04-api-reference/01-components/image-legacy.mdx Set up a custom cloud provider (like imgix) for image optimization instead of Next.js built-in API. Configure the loader type and path prefix to enable relative URLs that automatically generate correct absolute URLs for your provider. ```javascript module.exports = { images: { loader: 'imgix', path: 'https://example.com/myaccount/', }, } ``` -------------------------------- ### Configure devIndicators Position and Visibility Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/devIndicators.mdx TypeScript type definition for devIndicators configuration. Accepts a boolean false to hide the indicator or an object with optional position property. Position defaults to 'bottom-left' and can be set to any of the four corners. The indicator remains visible during development to show route rendering status. ```typescript devIndicators: false | { position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left', // defaults to 'bottom-left', } ``` -------------------------------- ### Contentful Image Loader Configuration Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/images.mdx Configures a custom loader for Contentful's Images API using URL search parameters to set image format, width, and quality for optimization. ```javascript // Docs: https://www.contentful.com/developers/docs/references/images-api/ export default function contentfulLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('fm', 'webp') url.searchParams.set('w', width.toString()) url.searchParams.set('q', (quality || 75).toString()) return url.href } ``` -------------------------------- ### API Routes Configuration and Limitations Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx Understand the constraints and configuration options for API Routes in Next.js, including CORS behavior, static export compatibility, and pageExtensions configuration. ```APIDOC ## API Routes Configuration ### Description Key considerations, limitations, and configuration options for Next.js API Routes. ### Important Limitations #### CORS Headers - **Default Behavior**: API Routes do not specify CORS headers by default - **Result**: Same-origin only - requests from different domains will be blocked - **Solution**: Use CORS request helpers or manually set CORS headers in your response - **Example**: See [API Routes with CORS](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors) #### Static Exports - **Limitation**: API Routes cannot be used with static exports - **Alternative**: Use Route Handlers in the App Router instead #### pageExtensions Configuration - **Affected By**: The `pageExtensions` configuration in `next.config.js` - **Impact**: API Routes follow the same file extension rules as pages - **Configuration**: Set custom extensions via `pageExtensions` if needed ### When to Use Alternatives - **App Router Projects**: Use [Route Handlers](/docs/app/api-reference/file-conventions/route) instead of API Routes - **Server-side Logic**: Use [Server Components](/docs/app/getting-started/server-and-client-components) for data fetching - **Static Generation**: Use [Route Handlers](/docs/app/api-reference/file-conventions/route) for App Router ### File Structure ``` pages/ api/ hello.ts → GET /api/hello users/ [id].ts → GET /api/users/[id] [...slug].ts → Catch-all routes ``` ### Example: Enabling CORS Wrap your handler with CORS middleware to handle cross-origin requests. See examples in the Next.js repository. ``` -------------------------------- ### Configure CSP Header in next.config.js without Nonces Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/content-security-policy.mdx Sets up a Content Security Policy header directly in the Next.js configuration file for applications that do not require nonces. The configuration includes environment-specific handling for development mode, allowing unsafe-eval in development while maintaining strict CSP in production. This approach works with next.config.js and applies the CSP header to all routes. ```javascript const isDev = process.env.NODE_ENV === 'development' const cspHeader = ` default-src 'self'; script-src 'self' 'unsafe-inline'${isDev ? " 'unsafe-eval'" : ''}; 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, ''), }, ], }, ] }, } ``` -------------------------------- ### Configure React Compiler Annotation Mode Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/reactCompiler.mdx Configure the React Compiler to run in 'annotation' mode, allowing opt-in compilation of specific components using the 'use memo' directive. This provides fine-grained control over which components are optimized. ```typescript import type { NextConfig } from 'next' const nextConfig: NextConfig = { reactCompiler: { compilationMode: 'annotation', }, } export default nextConfig ``` ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { reactCompiler: { compilationMode: 'annotation', }, } module.exports = nextConfig ``` -------------------------------- ### Configure cacheComponents in Next.js 16 Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-16.mdx Shows the new cacheComponents configuration option in Next.js 16 that replaces the experimental.dynamicIO flag from Next.js 15. This is a top-level configuration property that should be set to true. ```javascript // Next.js 16 - use cacheComponents instead module.exports = { cacheComponents: true, } ``` -------------------------------- ### Configure bundlePagesRouterDependencies in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-15.mdx Rename the experimental bundlePagesExternals configuration to the now-stable bundlePagesRouterDependencies option in your Next.js configuration file. This setting controls dependency bundling behavior for the Pages Router. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { // Before experimental: { bundlePagesExternals: true, }, // After bundlePagesRouterDependencies: true, } module.exports = nextConfig ``` -------------------------------- ### Export icon size configuration in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/01-metadata/app-icons.mdx Configure icon dimensions by exporting a size object with width and height properties from icon or apple-icon route files. This metadata generates appropriate link tags in the HTML head with the specified dimensions. Supports both TypeScript and JavaScript implementations. ```typescript export const size = { width: 32, height: 32 } export default function Icon() {} ``` ```javascript export const size = { width: 32, height: 32 } export default function Icon() {} ``` -------------------------------- ### Configure Turbopack as top-level option in Next.js 16 Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-16.mdx Set up Turbopack configuration at the top level of nextConfig in Next.js 16. This is the new standard location for Turbopack configuration options. ```typescript import type { NextConfig } from 'next' // Next.js 16 - turbopack at the top level of nextConfig const nextConfig: NextConfig = { turbopack: { // options }, } export default nextConfig ``` -------------------------------- ### Next.js Adapter Configuration Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx Configures the path to a custom adapter module in `next.config.js` using `experimental.adapterPath`. ```APIDOC ## CONFIGURATION experimental.adapterPath ### Description Configure a custom adapter module for Next.js by specifying its path in `experimental.adapterPath` within `next.config.js`. This allows custom logic to hook into the Next.js build process. ### Method CONFIGURATION ### Endpoint next.config.js ### Parameters #### Request Body - **experimental.adapterPath** (string) - Required - Path to the custom adapter module. Example: `require.resolve('./my-adapter.js')` ### Request Example ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { adapterPath: require.resolve('./my-adapter.js'), }, } module.exports = nextConfig ``` ### Response #### Success Response (N/A) - **N/A** (N/A) - This is a configuration, not an API call with a direct response. #### Response Example ```json // No direct response, affects Next.js build behavior ``` ``` -------------------------------- ### Configure Build Adapters API in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-16.mdx Configure custom build adapters using the Build Adapters API (alpha) to hook into the Next.js build process. This allows deployment platforms and custom integrations to modify Next.js configuration or process build output by specifying the adapter path in the experimental configuration. ```javascript const nextConfig = { experimental: { adapterPath: require.resolve('./my-adapter.js'), }, } module.exports = nextConfig ``` -------------------------------- ### Fastly Image Loader Configuration Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/images.mdx Implements a custom loader for Fastly's image optimization service using URL parameters to configure automatic format conversion, width, and quality settings. ```javascript // Docs: https://developer.fastly.com/reference/io/ export default function fastlyLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('auto', 'webp') url.searchParams.set('width', width.toString()) url.searchParams.set('quality', (quality || 75).toString()) return url.href } ``` -------------------------------- ### Configure Jest with Next.js Compiler Source: https://github.com/vercel/next.js/blob/canary/docs/03-architecture/nextjs-compiler.mdx Setup Jest configuration file to work seamlessly with Next.js Compiler. Uses nextJest helper from 'next/jest' to automatically configure Jest with SWC transforms, environment variables, and Next.js-specific settings. ```javascript const nextJest = require('next/jest') const createJestConfig = nextJest({ dir: './' }) const customJestConfig = { setupFilesAfterEnv: ['/jest.setup.js'], } module.exports = createJestConfig(customJestConfig) ``` -------------------------------- ### Next.js Configuration: serverExternalPackages Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/04-api-reference/04-config/01-next-config-js/serverExternalPackages.mdx This configuration option allows you to specify a list of package names that should be excluded from the automatic dependency bundling process in Next.js, particularly for the Pages Router. When a package is listed here, Next.js will use native Node.js `require` to resolve it instead of bundling it. ```APIDOC ## Configuration Key: serverExternalPackages ### Description This configuration option allows you to specify a list of package names that should be excluded from the automatic dependency bundling process in Next.js, particularly for the Pages Router. When a package is listed here, Next.js will use native Node.js `require` to resolve it instead of bundling it. This is useful for packages that have native Node.js bindings or other specific requirements that prevent them from being bundled efficiently. ### Configuration Path `next.config.js` (Root level property) ### Type `Array` ### Properties - **serverExternalPackages** (Array) - Required - An array of strings, where each string is the name of a Node.js package to be excluded from Next.js's automatic bundling. ### Example Usage ```javascript // next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { serverExternalPackages: ['@acme/ui'], } module.exports = nextConfig ``` ### Notes Next.js automatically opts out a short list of popular packages that are known to have compatibility issues with bundling. These packages are listed in the Next.js repository's `packages/next/src/lib/server-external-packages.jsonc`. Some examples of these automatically opted-out packages include: - `@alinea/generated` - `@appsignal/nodejs` - `@aws-sdk/client-s3` - `@blockfrost/blockfrost-js` - `@highlight-run/node` - `@huggingface/transformers` - `@libsql/client` - `@mikro-orm/core` - `@node-rs/argon2` - `@prisma/client` - `@react-pdf/renderer` - `@sentry/profiling-node` - `@sparticuz/chromium` - `@swc/core` - `@xenova/transformers` - `argon2` - `autoprefixer` - `aws-crt` - `bcrypt` - `better-sqlite3` - `canvas` - `chromadb-default-embed` - `config` - `cpu-features` - `cypress` - `dd-trace` - `eslint` - `express` - `firebase-admin` - `htmlrewriter` - `import-in-the-middle` - `isolated-vm` - `jest` - `jsdom` - `keyv` - `libsql` - `mdx-bundler` - `mongodb` - `mongoose` - `newrelic` - `next-mdx-remote` - `next-seo` - `node-cron` - `node-pty` - `node-web-audio-api` - `onnxruntime-node` - `oslo` - `pg` - `pino` - `pino-pretty` - `pino-roll` - `playwright` - `playwright-core` - `postcss` - `prettier` - `prisma` - `puppeteer-core` - `puppeteer` - `ravendb` - `require-in-the-middle` - `rimraf` - `sharp` - `shiki` - `sqlite3` - `thread-stream` - `ts-morph` - `ts-node` - `typescript` - `vscode-oniguruma` - `webpack` - `websocket` - `zeromq` ``` -------------------------------- ### Configure Permissions-Policy Header Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/headers.mdx Controls which browser features and APIs can be accessed by the application. Disables camera, microphone, geolocation, and browsing-topics in this configuration. This header (formerly Feature-Policy) provides granular control over feature access. ```javascript { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()' } ``` -------------------------------- ### Set Custom Build Directory with distDir in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/distDir.mdx Configure the distDir property in next.config.js to specify a custom build output directory. The specified directory must remain within the project root and cannot use relative paths like ../build. After configuration, running 'next build' will output to the custom directory instead of the default .next folder. ```javascript module.exports = { distDir: 'build', } ``` -------------------------------- ### Configure VS Code Launch Settings for Next.js Debugging Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/debugging.mdx This JSON configuration file (`.vscode/launch.json`) sets up multiple debug profiles for a Next.js application in VS Code. It includes configurations for debugging server-side Node.js processes, client-side code in Chrome or Firefox, and a comprehensive full-stack debugging setup. The Firefox Debugger extension is required for the Firefox client-side debugging configuration. ```json { "version": "0.2.0", "configurations": [ { "name": "Next.js: debug server-side", "type": "node-terminal", "request": "launch", "command": "npm run dev -- --inspect" }, { "name": "Next.js: debug client-side", "type": "chrome", "request": "launch", "url": "http://localhost:3000" }, { "name": "Next.js: debug client-side (Firefox)", "type": "firefox", "request": "launch", "url": "http://localhost:3000", "reAttach": true, "pathMappings": [ { "url": "webpack://_N_E", "path": "${workspaceFolder}" } ] }, { "name": "Next.js: debug full stack", "type": "node", "request": "launch", "program": "${workspaceFolder}/node_modules/next/dist/bin/next", "runtimeArgs": ["--inspect"], "skipFiles": ["/**"], "serverReadyAction": { "action": "debugWithEdge", "killOnServerStop": true, "pattern": "- Local:.+(https?://.+)", "uriFormat": "%s", "webRoot": "${workspaceFolder}" } } ] } ``` -------------------------------- ### Configure Rewrites with i18n Support in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/rewrites.mdx Configure URL rewrites with internationalization (i18n) support in next.config.js, where source and destination paths are automatically prefixed to handle configured locales. Use locale: false to disable automatic locale handling and manually control locale prefixing in source and destination paths. ```javascript module.exports = { i18n: { locales: ['en', 'fr', 'de'], defaultLocale: 'en', }, async rewrites() { return [ { source: '/with-locale', // automatically handles all locales destination: '/another', // automatically passes the locale on }, { // does not handle locales automatically since locale: false is set source: '/nl/with-locale-manual', destination: '/nl/another', locale: false, }, { // this matches '/' since `en` is the defaultLocale source: '/en', destination: '/en/another', locale: false, }, { // it's possible to match all locales even when locale: false is set source: '/:locale/api-alias/:path*', destination: '/api/:path*', locale: false, }, { // this gets converted to /(en|fr|de)/(.*) so will not match the top-level // `/` or `/fr` routes like /:path* would source: '/(.*)', destination: '/another', }, ] }, } ``` -------------------------------- ### Type Check Next.js Configuration with TypeScript (`next.config.ts`) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/02-typescript.mdx Demonstrates how to use TypeScript for type checking `next.js` configuration files by using a `next.config.ts` file. It imports the `NextConfig` type from the `next` package to ensure the configuration object adheres to the expected structure and properties. ```typescript import type { NextConfig } from 'next' const nextConfig: NextConfig = { /* config options here */ } export default nextConfig ``` -------------------------------- ### Configure Consistent Build ID in Next.js next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/self-hosting.mdx Configure the `generateBuildId` function in your `next.config.js` to produce a consistent build ID. This is critical for self-hosting scenarios where the application is rebuilt across different deployment stages, ensuring that the same build version is used across multiple containers to prevent inconsistencies. ```javascript module.exports = { generateBuildId: async () => { // This could be anything, using the latest git hash return process.env.GIT_HASH }, } ``` -------------------------------- ### Update Next.js Image Configuration: Deprecated `domains` vs. Recommended `remotePatterns` Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-16.mdx This snippet demonstrates the deprecated `images.domains` configuration for Next.js image optimization and its recommended replacement, `images.remotePatterns`. The new `remotePatterns` configuration offers enhanced security by allowing more granular control over image sources, requiring specification of protocol and hostname. ```javascript // image.domains is deprecated module.exports = { images: { domains: ['example.com'], }, } ``` ```javascript // Use image.remotePatterns instead module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 'example.com', }, ], }, } ``` -------------------------------- ### Session Management Configuration Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/authentication.mdx Configures session management for Next.js applications with environment variables and secret key generation. This setup supports both stateless (cookie-based) and database session approaches with proper encryption and security. ```APIDOC ## Session Management Setup ### Description Initializes session management infrastructure for authentication state persistence across requests. Supports both stateless sessions (cookie-based) and database sessions for different security and scalability requirements. ### Configuration Steps #### 1. Generate Secret Key Generate a cryptographic secret key for signing sessions: ```bash openssl rand -base64 32 ``` #### 2. Environment Variables Store the generated secret key in environment configuration: **File: .env** ``` SESSION_SECRET=your_secret_key ``` #### 3. Reference Secret Key in Code Access the secret key in your session management logic: **File: app/lib/session.js** ```javascript const secretKey = process.env.SESSION_SECRET ``` ### Session Types #### Stateless Sessions - Session data or token stored in browser cookies - Cookie sent with each request for server verification - Simpler implementation but requires careful security practices - Recommended session libraries: iron-session, Jose #### Database Sessions - Session data stored in database - Browser receives only encrypted session ID - More secure but requires additional server resources - Better for complex authentication scenarios ### Security Considerations - Store SESSION_SECRET as environment variable (never commit to version control) - Use HTTPS in production to protect cookie transmission - Implement session expiration and refresh mechanisms - Consider using established session management libraries for production applications ``` -------------------------------- ### Configure Module Path Aliases in TypeScript/JavaScript Config Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/testing/jest.mdx Sets up path aliases in tsconfig.json or jsconfig.json to enable absolute imports. Defines base URL and path mappings that must be mirrored in Jest's moduleNameMapper configuration. ```json { "compilerOptions": { "module": "esnext", "moduleResolution": "bundler", "baseUrl": "./", "paths": { "@/components/*": ["components/*"] } } } ``` -------------------------------- ### Enable trailing slash with trailingSlash config Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/exportPathMap.mdx Configure Next.js to export pages as index.html files with trailing slashes by enabling the trailingSlash option in next.config.js. This makes /about become /about/index.html and routable via /about/. ```javascript module.exports = { trailingSlash: true, } ``` -------------------------------- ### Configure crossOrigin in Next.js Config Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/crossOrigin.mdx Set the crossOrigin option in next.config.js to add crossOrigin attributes to all script tags generated by next/script component. This controls how cross-origin requests are handled by the browser. The configuration accepts 'anonymous' or 'use-credentials' as valid values. ```javascript module.exports = { crossOrigin: 'anonymous', } ``` -------------------------------- ### Configure Next.js i18n for Initial Setup with Domain Routing Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/02-guides/internationalization.mdx This configuration in `next.config.js` initializes Next.js i18n support. It defines supported locales, a default locale, and sets up domain-specific routing with examples for different top-level domains and local HTTP testing. ```javascript module.exports = { i18n: { // These are all the locales you want to support in // your application locales: ['en-US', 'fr', 'nl-NL'], // This is the default locale you want to be used when visiting // a non-locale prefixed path e.g. `/hello` defaultLocale: 'en-US', // This is a list of locale domains and the default locale they // should handle (these are only required when setting up domain routing) // Note: subdomains must be included in the domain value to be matched e.g. "fr.example.com". domains: [ { domain: 'example.com', defaultLocale: 'en-US', }, { domain: 'example.nl', defaultLocale: 'nl-NL', }, { domain: 'example.fr', defaultLocale: 'fr', // an optional http field can also be used to test // locale domains locally with http instead of https http: true, }, ], }, } ``` -------------------------------- ### Configure Browserslist for Next.js Browser Targeting Source: https://github.com/vercel/next.js/blob/canary/docs/03-architecture/supported-browsers.mdx This snippet demonstrates how to configure Browserslist in your `package.json` file. Next.js uses this configuration to target specific browser versions for compilation and feature support, ensuring compatibility with your desired browser environment. ```json { "browserslist": ["chrome 111", "edge 111", "firefox 111", "safari 16.4"] } ``` -------------------------------- ### Configure Advanced Styled Components Options in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/03-architecture/nextjs-compiler.mdx Advanced configuration for styled-components compilation in Next.js Compiler with granular control over individual transformation properties. Allows customization of display names, SSR, file names, import paths, and other compilation behaviors. ```javascript module.exports = { compiler: { styledComponents: { displayName?: boolean, ssr?: boolean, fileName?: boolean, topLevelImportPaths?: string[], meaninglessFileNames?: string[], minify?: boolean, transpileTemplateLiterals?: boolean, namespace?: string, pure?: boolean, cssProp?: boolean, }, }, } ``` -------------------------------- ### Configure allowedOrigins for Server Actions Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/serverActions.mdx Set extra safe origin domains from which Server Actions can be invoked. Next.js validates the origin against the host domain to prevent CSRF attacks. If not provided, only same-origin requests are allowed. ```javascript /** @type {import('next').NextConfig} */ module.exports = { experimental: { serverActions: { allowedOrigins: ['my-proxy.com', '*.my-proxy.com'], }, }, } ``` -------------------------------- ### Interoperable Object-Based PostCSS Configuration for Next.js (JavaScript) Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/02-guides/post-css.mdx This snippet presents an object-based format for `postcss.config.js` that ensures interoperability with other non-Next.js tools in the same project. It defines plugins as keys in an object, allowing for a consistent configuration across different build systems. ```javascript module.exports = { plugins: { 'postcss-flexbugs-fixes': {}, 'postcss-preset-env': { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': false, }, }, }, } ``` -------------------------------- ### Configure serverExternalPackages in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-15.mdx Update the experimental serverComponentsExternalPackages configuration to use the stable serverExternalPackages option. This setting specifies which packages should be treated as external when used in Server Components. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { // Before experimental: { serverComponentsExternalPackages: ['package-name'], }, // After serverExternalPackages: ['package-name'], } module.exports = nextConfig ``` -------------------------------- ### Configure Custom tsconfig Path in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/02-typescript.mdx Set a custom TypeScript configuration file path in next.config.ts using the typescript.tsconfigPath option. This allows Next.js to use an alternate tsconfig file for builds while keeping IDE diagnostics separate. Useful for monorepos or relaxing type checks in production builds. ```typescript import type { NextConfig } from 'next' const nextConfig: NextConfig = { typescript: { tsconfigPath: 'tsconfig.build.json', }, } export default nextConfig ``` -------------------------------- ### Default PostCSS Configuration for Next.js (JSON) Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/02-guides/post-css.mdx This snippet shows the default PostCSS configuration used by Next.js, defined in a `postcss.config.json` file. It includes plugins like `postcss-flexbugs-fixes` and `postcss-preset-env` with specific settings for `autoprefixer` and `custom-properties`. ```json { "plugins": [ "postcss-flexbugs-fixes", [ "postcss-preset-env", { "autoprefixer": { "flexbox": "no-2009" }, "stage": 3, "features": { "custom-properties": false } } ] ] } ``` -------------------------------- ### Generate Basic Jest Configuration File Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/testing/jest.mdx Run one of these commands to generate a basic Jest configuration file (either `jest.config.ts` or `jest.config.js`) for your project, guided by a series of prompts. ```bash npm init jest@latest ``` ```bash yarn create jest@latest ``` ```bash pnpm create jest@latest ``` -------------------------------- ### Configure Server Runtime Config in Next.js 15 Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-16.mdx Demonstrates the deprecated serverRuntimeConfig and publicRuntimeConfig pattern used in Next.js 15. This approach combined configuration settings in next.config.js and accessed them via getConfig(). This pattern has been replaced with environment variables in Next.js 16. ```javascript module.exports = { serverRuntimeConfig: { dbUrl: process.env.DATABASE_URL, }, publicRuntimeConfig: { apiUrl: '/api', }, } ``` -------------------------------- ### Configure Relay with Next.js Compiler Source: https://github.com/vercel/next.js/blob/canary/docs/03-architecture/nextjs-compiler.mdx Enable Relay support in Next.js Compiler by configuring relay options in next.config.js. Specifies the source directory, artifact output location, language, and module settings for the relay-compiler integration. ```javascript module.exports = { compiler: { relay: { src: './', artifactDirectory: './__generated__', language: 'typescript', eagerEsModules: false, }, }, } ``` -------------------------------- ### Configure Custom Webpack in Next.js `next.config.ts` Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/migrating/from-create-react-app.mdx Extend Next.js's webpack configuration within `next.config.ts` to migrate custom webpack or Babel setups from Create React App. This configuration requires the `--webpack` flag for the development server. ```typescript import { NextConfig } from 'next'\n\nconst nextConfig: NextConfig = {\n webpack: (config, { isServer }) => {\n // Modify the webpack config here\n return config\n },\n}\n\nexport default nextConfig ``` -------------------------------- ### Configure assetPrefix with rewrites for Next.js versions before 15 Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/multi-zones.mdx For Next.js versions older than 15, configure both assetPrefix and rewrites to handle static assets. The beforeFiles rewrite maps the prefixed assets path to the internal _next path. This additional configuration is no longer necessary in Next.js 15 and later. ```JavaScript /** @type {import('next').NextConfig} */ const nextConfig = { assetPrefix: '/blog-static', async rewrites() { return { beforeFiles: [ { source: '/blog-static/_next/:path+', destination: '/_next/:path+', }, ], } }, } ``` -------------------------------- ### Configure Next.js onDemandEntries in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/01-next-config-js/onDemandEntries.mdx This configuration object in `next.config.js` allows you to customize the behavior of Next.js's on-demand entries. It defines `maxInactiveAge`, the duration (in milliseconds) for which a page remains in the server's buffer, and `pagesBufferLength`, the maximum number of pages to keep in memory simultaneously without disposal, optimizing development server performance. ```javascript module.exports = { onDemandEntries: { // period (in ms) where the server will keep pages in the buffer maxInactiveAge: 25 * 1000, // number of pages that should be kept simultaneously without being disposed pagesBufferLength: 2, }, } ``` -------------------------------- ### metadataBase TypeScript configuration in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/04-functions/generate-metadata.mdx TypeScript version of metadataBase configuration in app/layout.tsx. Demonstrates proper typing using the Metadata type from 'next' package. This approach is recommended for TypeScript projects to ensure type safety when configuring metadata base URLs. ```tsx import type { Metadata } from 'next' export const metadata: Metadata = { metadataBase: new URL('https://acme.com'), } ```