### Start the Standalone Server
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Execute the generated server.js file using Node.js to start the application.
```bash
node .next/standalone/server.js
```
--------------------------------
### Install babel-plugin-react-compiler
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler
Install the required Babel plugin using your preferred package manager.
```bash
pnpm add -D babel-plugin-react-compiler
```
```bash
npm install -D babel-plugin-react-compiler
```
```bash
yarn add -D babel-plugin-react-compiler
```
```bash
bun add -D babel-plugin-react-compiler
```
--------------------------------
### Implement an injected instrumentation module
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/instrumentationClientInject
Create a module that performs setup at load time and optionally exports an onRouterTransitionStart function for navigation tracking.
```javascript
// Side-effectful setup runs at load time.
setupSentry()
export function onRouterTransitionStart(url, navigationType) {
recordNavigationBreadcrumb(url, navigationType)
}
```
--------------------------------
### Client-side Console Log Example
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/logging
A client component example that triggers a console log for terminal forwarding.
```tsx
'use client'
export default function Home() {
return (
)
}
```
--------------------------------
### Example of asset path transformation
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix
Shows how a standard internal request path is transformed when an assetPrefix is configured.
```text
/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
```
```text
https://cdn.mydomain.com/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
```
--------------------------------
### Install TypeScript 7
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/useTypeScriptCli
Commands to install TypeScript 7 as a development dependency using various package managers.
```bash
pnpm add -D typescript@^7
```
```bash
npm install -D typescript@^7
```
```bash
yarn add -D typescript@^7
```
```bash
bun add -D typescript@^7
```
--------------------------------
### Re-configure htmlLimitedBots
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/htmlLimitedBots
An alternative example showing the configuration structure for overriding the default bot list.
```ts
const config: NextConfig = {
htmlLimitedBots: /MySpecialBot|MyAnotherSpecialBot|SimpleCrawler/,
}
export default config
```
```js
module.exports = {
htmlLimitedBots: /MySpecialBot|MyAnotherSpecialBot|SimpleCrawler/,
}
```
--------------------------------
### Use Skypack Modules
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/urlImports
Example of importing a library from Skypack and using it within a React component.
```js
import confetti from 'https://cdn.skypack.dev/canvas-confetti'
import { useEffect } from 'react'
export default () => {
useEffect(() => {
confetti()
})
return
Hello
}
```
--------------------------------
### Check build output for route status
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/devIndicators
Example of terminal output when running next build --debug to identify static and dynamic routes.
```bash
Route (app)
┌ ○ /_not-found
└ ƒ /products/[id]
○ (Static) prerendered as static content
ƒ (Dynamic) server-rendered on demand
```
--------------------------------
### Example Server Function Terminal Output
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/logging
The format displayed in the terminal when Server Function logging is enabled.
```bash
POST /
└─ ƒ myAction(arg1, arg2) in 5ms app/actions.ts
```
--------------------------------
### get(key, ctx)
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath
Retrieves a cached value based on the provided key and context.
```APIDOC
## get(key, ctx)
### Description
Retrieves a cached value from the storage. Returns the cached value or null if not found.
### Parameters
- **key** (string) - Required - The key to the cached value.
- **ctx** (object) - Required - Context including the cache entry kind (e.g., 'APP_PAGE', 'APP_ROUTE', 'PAGES', 'FETCH', 'IMAGE').
```
--------------------------------
### Configure tracing with a src directory
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Demonstrates how to reference paths within a src directory for file tracing configuration.
```javascript
module.exports = {
outputFileTracingIncludes: {
'/products/*': ['src/lib/payments/**/*'],
'/*': ['src/config/runtime/**/*.json'],
},
outputFileTracingExcludes: {
'/api/*': ['src/temp/**/*', 'public/large-logs/**/*'],
},
}
```
--------------------------------
### Configure X-DNS-Prefetch-Control header
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
Enable DNS prefetching to reduce latency for external resources.
```js
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
}
```
--------------------------------
### Implement CacheHandler get() Method
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers
The get method retrieves a cache entry by key and validates its expiration time.
```ts
get(cacheKey: string, softTags: string[]): Promise
```
```js
const cacheHandler = {
async get(cacheKey, softTags) {
const entry = cache.get(cacheKey)
if (!entry) return undefined
// Check if expired
const now = Date.now()
if (now > entry.timestamp + entry.revalidate * 1000) {
return undefined
}
return entry
},
}
```
--------------------------------
### refreshTags()
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers
Called periodically before starting a new request to sync with external tag services.
```APIDOC
## refreshTags()
### Description
Used to coordinate cache invalidation across multiple instances or services. For in-memory caches, this can be a no-op.
### Returns
- **Promise**
```
--------------------------------
### Use Path Parameters in Headers
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
Shows how to use matched path parameters within header keys and values.
```javascript
module.exports = {
headers() {
return [
{
source: '/blog/:slug',
headers: [
{
key: 'x-slug',
value: ':slug', // Matched parameters can be used in the value
},
{
key: 'x-slug-:slug', // Matched parameters can be used in the key
value: 'my other custom header value',
},
],
},
]
},
}
```
--------------------------------
### Configure based on build phase
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js
Import constants from next/constants to apply conditional configuration based on the current environment or build phase.
```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 basic path matching in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
Use parameters in the source path to capture segments and reuse them in the destination.
```javascript
module.exports = {
redirects() {
return [
{
source: '/old-blog/:slug',
destination: '/news/:slug', // Matched parameters can be used in the destination
permanent: true,
},
]
},
}
```
--------------------------------
### Define configuration using ECMAScript modules
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js
Use next.config.mjs to leverage ES module syntax for configuration.
```javascript
// @ts-check
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
export default nextConfig
```
--------------------------------
### Combine outputFileTracingRoot with includes
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Configures the tracing root to the monorepo base while including specific shared assets.
```javascript
const path = require('path')
module.exports = {
// Trace from the monorepo root
outputFileTracingRoot: path.join(__dirname, '../../'),
outputFileTracingIncludes: {
'/route1': ['../shared/assets/**/*'],
},
}
```
--------------------------------
### Configure headers with basePath
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
Demonstrates how to control whether the basePath is automatically prefixed to header source paths using the basePath property.
```javascript
module.exports = {
basePath: '/docs',
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,
},
]
},
}
```
--------------------------------
### get(cacheKey: string, softTags: string[])
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers
Retrieves a cache entry for the given cache key. Returns a CacheEntry object if found, or undefined if not found or expired.
```APIDOC
## get(cacheKey: string, softTags: string[])
### Description
Retrieve a cache entry for the given cache key. Your implementation should check if the entry has expired based on the revalidate time.
### Parameters
- **cacheKey** (string) - The unique key for the cache entry.
- **softTags** (string[]) - Implicit tags derived from the route path.
### Returns
- **Promise** - The cache entry if found and valid, otherwise undefined.
```
--------------------------------
### Configure Nitrogen AIO Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Custom loader for Nitrogen AIO integration.
```js
// Docs: https://docs.n7.io/aio/intergrations/
export default function aioLoader({ src, width, quality }) {
const url = new URL(src, window.location.href)
const params = url.searchParams
const aioParams = params.getAll('aio')
aioParams.push(`w-${width}`)
if (quality) {
aioParams.push(`q-${quality.toString()}`)
}
params.set('aio', aioParams.join(';'))
return url.href
}
```
--------------------------------
### Manually Copy Static Assets
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Use the cp command to move public and static folders into the standalone directory after building.
```bash
cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/
```
--------------------------------
### Configure PixelBin Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Constructs a PixelBin transformation URL using cloud name, resize, and compression operations.
```js
// Doc (Resize): https://www.pixelbin.io/docs/transformations/basic/resize/#width-w
// Doc (Optimise): https://www.pixelbin.io/docs/optimizations/quality/#image-quality-when-delivering
// Doc (Auto Format Delivery): https://www.pixelbin.io/docs/optimizations/format/#automatic-format-selection-with-f_auto-url-parameter
export default function pixelBinLoader({ src, width, quality }) {
const name = ''
const opt = `t.resize(w:${width})~t.compress(q:${quality || 75})`
return `https://cdn.pixelbin.io/v2/${name}/${opt}/${src}?f_auto=true`
}
```
--------------------------------
### Apply tracing configuration to all routes
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Uses the global '/*' key to apply file inclusion rules to every route in the application.
```javascript
module.exports = {
outputFileTracingIncludes: {
'/*': ['src/i18n/locales/**/*.json'],
},
}
```
--------------------------------
### Define configuration as a function
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js
Export a function to access the current build phase and default configuration object.
```javascript
// @ts-check
export default (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig
}
```
--------------------------------
### Configure onDemandEntries in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/onDemandEntries
Adjust the maxInactiveAge and pagesBufferLength to control page disposal behavior in development.
```js
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,
},
}
```
--------------------------------
### Configure ImageEngine Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Calculates compression based on quality and applies ImageEngine directives.
```js
// Docs: https://support.imageengine.io/hc/en-us/articles/360058880672-Directives
export default function imageengineLoader({ src, width, quality }) {
const compression = 100 - (quality || 50)
const params = [`w_${width}`, `cmpr_${compression}`)]
return `https://example.com${src}?imgeng=/${params.join('/')`
}
```
--------------------------------
### Configure AWS CloudFront Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Constructs a URL with format, width, and quality parameters for CloudFront image optimization.
```js
// Docs: https://aws.amazon.com/developer/application-security-performance/articles/image-optimization
export default function cloudfrontLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('format', 'auto')
url.searchParams.set('width', width.toString())
url.searchParams.set('quality', (quality || 75).toString())
return url.href
}
```
--------------------------------
### Configure Fetch Logging
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/logging
Enable full URL logging for fetch requests in development mode.
```js
module.exports = {
logging: {
fetches: {
fullUrl: true,
},
},
}
```
--------------------------------
### Configure Imgix Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Preserves existing URL parameters while overriding width, quality, and fit for Imgix.
```js
// Demo: https://static.imgix.net/daisy.png?format=auto&fit=max&w=300
export default function imgixLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
const params = url.searchParams
params.set('auto', params.getAll('auto').join(',') || 'format')
params.set('fit', params.get('fit') || 'max')
params.set('w', params.get('w') || width.toString())
params.set('q', (quality || 50).toString())
return url.href
}
```
--------------------------------
### Configure useLightningcss in next.config
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/useLightningcss
Enable or disable Lightning CSS support within the experimental configuration block.
```ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useLightningcss: false, // default, ignored on Turbopack
},
}
export default nextConfig
```
```js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useLightningcss: true, // disables PostCSS on webpack
},
}
module.exports = nextConfig
```
--------------------------------
### Define basic configuration in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js
Use a default export in a CommonJS module to define static configuration options.
```javascript
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
}
module.exports = nextConfig
```
--------------------------------
### Configure Fastly Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Configures Fastly Image Optimizer parameters including webp auto-format, width, and quality.
```js
// 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 assetPrefix in next.config.mjs
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix
Use phase-based configuration to conditionally set the assetPrefix for production environments while keeping it undefined during development.
```js
// @ts-check
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
export default (phase) => {
const isDev = phase === PHASE_DEVELOPMENT_SERVER
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
assetPrefix: isDev ? undefined : 'https://cdn.mydomain.com',
}
return nextConfig
}
```
--------------------------------
### Define basic rewrites in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites
Use the rewrites function to return an array of source and destination path mappings.
```javascript
module.exports = {
rewrites() {
return [
{
source: '/about',
destination: '/',
},
]
},
}
```
--------------------------------
### Configure Akamai Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Uses the imwidth parameter to specify the image width for Akamai's Image Manager.
```js
// 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}`
}
```
--------------------------------
### Configure URL Imports in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/urlImports
Add allowed URL prefixes to the experimental configuration to enable external module imports.
```js
module.exports = {
experimental: {
urlImports: ['https://example.com/assets/', 'https://cdn.skypack.dev'],
},
}
```
--------------------------------
### Implement a basic in-memory cache handler
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers
Uses a Map to store cache entries. This implementation is for demonstration purposes and lacks production-grade features like LRU eviction.
```javascript
const cache = new Map()
const pendingSets = new Map()
module.exports = {
async get(cacheKey, softTags) {
// Wait for any pending set operation to complete
const pendingPromise = pendingSets.get(cacheKey)
if (pendingPromise) {
await pendingPromise
}
const entry = cache.get(cacheKey)
if (!entry) {
return undefined
}
// Check if entry has expired
const now = Date.now()
if (now > entry.timestamp + entry.revalidate * 1000) {
return undefined
}
return entry
},
async set(cacheKey, pendingEntry) {
// Create a promise to track this set operation
let resolvePending
const pendingPromise = new Promise((resolve) => {
resolvePending = resolve
})
pendingSets.set(cacheKey, pendingPromise)
try {
// Wait for the entry to be ready
const entry = await pendingEntry
// Store the entry in the cache
cache.set(cacheKey, entry)
} finally {
resolvePending()
pendingSets.delete(cacheKey)
}
},
async refreshTags() {
// No-op for in-memory cache
},
async getExpiration(tags) {
// Return 0 to indicate no tags have been revalidated
return 0
},
async updateTags(tags, durations) {
// Implement tag-based invalidation
for (const [key, entry] of cache.entries()) {
if (entry.tags.some((tag) => tags.includes(tag))) {
cache.delete(key)
}
}
},
}
```
--------------------------------
### Include native or runtime assets globally
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Common pattern for ensuring native dependencies or runtime assets are included in the trace.
```javascript
module.exports = {
outputFileTracingIncludes: {
'/*': ['node_modules/sharp/**/*', 'node_modules/aws-crt/dist/bin/**/*'],
},
}
```
--------------------------------
### Configure headers with i18n support
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
Shows how to manage locale-aware header matching, including how to disable automatic locale prefixing for specific routes.
```javascript
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
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',
},
],
},
]
},
}
```
--------------------------------
### Import Assets via URL Constructor
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/urlImports
Use the URL constructor to reference external assets, which Next.js will resolve to a static path.
```js
const logo = new URL('https://example.com/assets/file.txt', import.meta.url)
console.log(logo.pathname)
// prints "/_next/static/media/file.a9727b5d.txt"
```
--------------------------------
### Enable Standalone Output in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Configure the output property to standalone to enable automatic file tracing and copying.
```js
module.exports = {
output: 'standalone',
}
```
--------------------------------
### Unit Test Next.js Routing Configurations
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js
Use unstable_getResponseFromNextConfig to verify headers, redirects, and rewrites in an experimental testing environment.
```js
import {
getRedirectUrl,
unstable_getResponseFromNextConfig,
} from 'next/experimental/testing/server'
const response = await unstable_getResponseFromNextConfig({
url: 'https://nextjs.org/test',
nextConfig: {
async redirects() {
return [{ source: '/test', destination: '/test2', permanent: false }]
},
},
})
expect(response.status).toEqual(307)
expect(getRedirectUrl(response)).toEqual('https://nextjs.org/test2')
```
--------------------------------
### Configure proxyClientMaxBodySize with string format
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/proxyClientMaxBodySize
Set the maximum body size using human-readable units like '1mb'.
```ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
proxyClientMaxBodySize: '1mb',
},
}
export default nextConfig
```
```js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
proxyClientMaxBodySize: '1mb',
},
}
module.exports = nextConfig
```
--------------------------------
### Configure Cloudflare Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Uses the cdn-cgi/image path to apply width, quality, and format transformations via Cloudflare.
```js
// Docs: https://developers.cloudflare.com/images/transform-images
export default function cloudflareLoader({ src, width, quality }) {
const params = [`width=${width}`, `quality=${quality || 75}`, 'format=auto']
return `https://example.com/cdn-cgi/image/${params.join(',')}/${src}`
}
```
--------------------------------
### Configure Static Generation Options
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/staticGeneration
Define experimental static generation settings within the next.config file to manage build performance and reliability.
```ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
staticGenerationRetryCount: 1,
staticGenerationMaxConcurrency: 8,
staticGenerationMinPagesPerWorker: 25,
},
}
export default nextConfig
```
```js
const nextConfig = {
experimental: {
staticGenerationRetryCount: 1,
staticGenerationMaxConcurrency: 8,
staticGenerationMinPagesPerWorker: 25,
},
}
export default nextConfig
```
--------------------------------
### Configure Sirv Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Custom loader for Sirv dynamic imaging. Requires the src, width, and quality parameters.
```js
// Docs: https://sirv.com/help/articles/dynamic-imaging/
export default function sirvLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
const params = url.searchParams
params.set('format', params.getAll('format').join(',') || 'optimal')
params.set('w', params.get('w') || width.toString())
params.set('q', (quality || 85).toString())
return url.href
}
```
--------------------------------
### Configure Contentful Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Sets webp format, width, and quality parameters for the Contentful Images API.
```js
// 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
}
```
--------------------------------
### Configure outputFileTracingRoot in a monorepo
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output
Sets the root directory for file tracing, allowing the inclusion of files located outside the current project directory.
```javascript
const path = require('path')
module.exports = {
// this includes files from the monorepo base two directories up
outputFileTracingRoot: path.join(__dirname, '../../'),
}
```
--------------------------------
### Configure Redirects with Header, Cookie, and Query Matching
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
Use the has and missing fields to conditionally apply redirects based on request headers, cookies, host, or query parameters.
```javascript
module.exports = {
redirects() {
return [
// if the header `x-redirect-me` is present,
// this redirect will be applied
{
source: '/:path((?!another-page$).*)',
has: [
{
type: 'header',
key: 'x-redirect-me',
},
],
permanent: false,
destination: '/another-page',
},
// if the header `x-do-not-redirect` is present,
// this redirect will NOT be applied
{
source: '/:path((?!another-page$).*)',
missing: [
{
type: 'header',
key: 'x-do-not-redirect',
},
],
permanent: false,
destination: '/another-page',
},
// if the source, query, and cookie are matched,
// this redirect will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the
// destination since value is provided and doesn't
// use a named capture group e.g. (?home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
permanent: false,
destination: '/another/:path*',
},
// if the header `x-authorized` is present and
// contains a matching value, this redirect will be applied
{
source: '/',
has: [
{
type: 'header',
key: 'x-authorized',
value: '(?yes|true)',
},
],
permanent: false,
destination: '/home?authorized=:authorized',
},
// if the host is `example.com`,
// this redirect will be applied
{
source: '/:path((?!another-page$).*)',
has: [
{
type: 'host',
value: 'example.com',
},
],
permanent: false,
destination: '/another-page',
},
]
},
}
```
--------------------------------
### Configure module resolution aliases
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack
Map import patterns to new destinations using the resolveAlias field in next.config.js.
```js
module.exports = {
turbopack: {
resolveAlias: {
underscore: 'lodash',
mocha: { browser: 'mocha/browser-entry.js' },
},
},
}
```
--------------------------------
### Import Modules from URLs
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/urlImports
Import modules directly from external URLs once the domain is allowed in the configuration.
```js
import { a, b, c } from 'https://example.com/assets/some/module.js'
```
--------------------------------
### Router Navigation Hook
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/instrumentationClientInject
Implementing the optional onRouterTransitionStart hook within an injected instrumentation module.
```APIDOC
## onRouterTransitionStart
### Description
An optional exported function from an injected module that is called during router transitions. Next.js composes these hooks and executes them in the order defined in `instrumentationClientInject`.
### Signature
`onRouterTransitionStart(url: string, navigationType: string)`
### Example
```js
// lib/sentry-client.js
setupSentry()
export function onRouterTransitionStart(url, navigationType) {
recordNavigationBreadcrumb(url, navigationType)
}
```
```
--------------------------------
### Enable React Compiler in next.config
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler
Enable the React Compiler by setting the reactCompiler option to true in your configuration file.
```typescript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
reactCompiler: true,
}
export default nextConfig
```
```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
reactCompiler: true,
}
module.exports = nextConfig
```
--------------------------------
### Configure Sanity Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Builds a Sanity CDN URL with project-specific identifiers and image transformation parameters.
```js
// Docs: https://www.sanity.io/docs/image-urls
export default function sanityLoader({ src, width, quality }) {
const prj = 'zp7mbokg'
const dataset = 'production'
const url = new URL(`https://cdn.sanity.io/images/${prj}/${dataset}${src}`)
url.searchParams.set('auto', 'format')
url.searchParams.set('fit', 'max')
url.searchParams.set('w', width.toString())
if (quality) {
url.searchParams.set('q', quality.toString())
}
return url.href
}
```
--------------------------------
### Build-time variable replacement
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/env
Next.js replaces process.env references with the actual values during the build process.
```jsx
return
The value of customKey is: {process.env.customKey}
```
```jsx
return
The value of customKey is: {'my-value'}
```
--------------------------------
### Configure Gumlet Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Sets format, width, and quality parameters for Gumlet image transformations.
```js
// Docs: https://docs.gumlet.com/reference/image-transform-size
export default function gumletLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('format', 'auto')
url.searchParams.set('w', width.toString())
url.searchParams.set('q', (quality || 75).toString())
return url.href
}
```
--------------------------------
### Configure instrumentationClientInject in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/instrumentationClientInject
Define instrumentation modules directly in the project configuration using npm packages or relative file paths.
```javascript
/** @type {import('next').NextConfig} */
module.exports = {
instrumentationClientInject: [
'my-analytics-package',
'./lib/sentry-client.js',
],
}
```
--------------------------------
### Configure Conditional Headers in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
Use the headers function to return an array of objects that define source paths and matching criteria for applying headers.
```js
module.exports = {
headers() {
return [
// if the header `x-add-header` is present,
// the `x-another-header` header will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-add-header',
},
],
headers: [
{
key: 'x-another-header',
value: 'hello',
},
],
},
// if the header `x-no-header` is not present,
// the `x-another-header` header will be applied
{
source: '/:path*',
missing: [
{
type: 'header',
key: 'x-no-header',
},
],
headers: [
{
key: 'x-another-header',
value: 'hello',
},
],
},
// if the source, query, and cookie are matched,
// the `x-authorized` header will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the
// header key/values since value is provided and
// doesn't use a named capture group e.g. (?home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
headers: [
{
key: 'x-authorized',
value: ':authorized',
},
],
},
// if the header `x-authorized` is present and
// contains a matching value, the `x-another-header` will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-authorized',
value: '(?yes|true)',
},
],
headers: [
{
key: 'x-another-header',
value: ':authorized',
},
],
},
// if the host is `example.com`,
// this header will be applied
{
source: '/:path*',
has: [
{
type: 'host',
value: 'example.com',
},
],
headers: [
{
key: 'x-another-header',
value: ':authorized',
},
],
},
]
},
}
```
--------------------------------
### Configure Supabase Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Custom loader for Supabase storage image transformations.
```js
// Docs: https://supabase.com/docs/guides/storage/image-transformations#nextjs-loader
export default function supabaseLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('width', width.toString())
url.searchParams.set('quality', (quality || 75).toString())
return url.href
}
```
--------------------------------
### Enable turbopackLocalPostcssConfig in next.config
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackLocalPostcssConfig
Configure the experimental flag in your Next.js configuration file to enable local PostCSS resolution.
```ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
turbopackLocalPostcssConfig: true,
},
}
export default nextConfig
```
```js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
turbopackLocalPostcssConfig: true,
},
}
module.exports = nextConfig
```
--------------------------------
### Enable authInterrupts in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/authInterrupts
Enable the experimental authInterrupts feature by setting it to true within the experimental object in your configuration file.
```ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
authInterrupts: true,
},
}
export default nextConfig
```
```js
module.exports = {
experimental: {
authInterrupts: true,
},
}
```
--------------------------------
### Configure wildcard path matching in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
Use the * modifier to match zero or more path segments.
```javascript
module.exports = {
redirects() {
return [
{
source: '/blog/:slug*',
destination: '/news/:slug*', // Matched parameters can be used in the destination
permanent: true,
},
]
},
}
```
--------------------------------
### Configure ImageKit.io Image Loader
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Custom loader for ImageKit.io transformation parameters.
```js
// Docs: https://imagekit.io/docs/image-transformation
export default function imageKitLoader({ src, width, quality }) {
const params = [`w-${width}`, `q-${quality || 80}`]
return `https://ik.imagekit.io/your_imagekit_id/${src}?tr=${params.join(',')}`
}
```
--------------------------------
### Configure instrumentationClientInject in a Next.js plugin
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/instrumentationClientInject
Use this pattern within a plugin to append instrumentation modules to an existing configuration.
```javascript
module.exports = function withMyInstrumentation(nextConfig = {}) {
return {
...nextConfig,
instrumentationClientInject: [
...(nextConfig.instrumentationClientInject ?? []),
'my-instrumentation-package/client',
],
}
}
```
--------------------------------
### Implement an external Redis cache handler
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers
Demonstrates how to serialize and store cache entries in Redis. Requires handling ReadableStream serialization for stored values.
```javascript
const { createClient } = require('redis')
const client = createClient({ url: process.env.REDIS_URL })
client.connect()
module.exports = {
async get(cacheKey, softTags) {
// Retrieve from Redis
const stored = await client.get(cacheKey)
if (!stored) return undefined
// Deserialize the entry
const data = JSON.parse(stored)
// Reconstruct the ReadableStream from stored data
return {
value: new ReadableStream({
start(controller) {
controller.enqueue(Buffer.from(data.value, 'base64'))
controller.close()
},
}),
tags: data.tags,
stale: data.stale,
timestamp: data.timestamp,
expire: data.expire,
revalidate: data.revalidate,
}
},
async set(cacheKey, pendingEntry) {
const entry = await pendingEntry
// Read the stream to get the data
const reader = entry.value.getReader()
const chunks = []
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
}
} finally {
reader.releaseLock()
}
// Combine chunks and serialize for Redis storage
const data = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)))
await client.set(
cacheKey,
JSON.stringify({
value: data.toString('base64'),
tags: entry.tags,
stale: entry.stale,
timestamp: entry.timestamp,
expire: entry.expire,
revalidate: entry.revalidate,
}),
{ EX: entry.expire } // Use Redis TTL for automatic expiration
)
},
async refreshTags() {
// No-op for basic Redis implementation
// Could sync with external tag service if needed
},
async getExpiration(tags) {
// Return 0 to indicate no tags have been revalidated
// Could query Redis for tag expiration timestamps if tracking them
return 0
},
async updateTags(tags, durations) {
// Implement tag-based invalidation if needed
// Could iterate over keys with matching tags and delete them
},
}
```
--------------------------------
### Configure htmlLimitedBots in next.config
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/htmlLimitedBots
Define a regex of user agents to receive blocking metadata. This overrides the default list provided by Next.js.
```ts
import type { NextConfig } from 'next'
const config: NextConfig = {
htmlLimitedBots: /MySpecialBot|MyAnotherSpecialBot|SimpleCrawler/,
}
export default config
```
```js
module.exports = {
htmlLimitedBots: /MySpecialBot|MyAnotherSpecialBot|SimpleCrawler/,
}
```
--------------------------------
### Configure custom image loader in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/images
Set the loader to 'custom' and specify the path to the loader file relative to the project root.
```javascript
module.exports = {
images: {
loader: 'custom',
loaderFile: './my/image/loader.js',
},
}
```
--------------------------------
### Configure generateBuildId in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/generateBuildId
Use this function to return a consistent build ID, such as a git hash, to identify the application version across different environments.
```jsx
module.exports = {
generateBuildId: async () => {
// This could be anything, using the latest git hash
return process.env.GIT_HASH
},
}
```
--------------------------------
### Configure transpilePackages in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/transpilePackages
Define the list of package names to be transpiled by Next.js within the configuration object.
```js
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['package-name', '@scope/pkg'],
}
module.exports = nextConfig
```
--------------------------------
### Configure webpack loaders for file extensions
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack
Map file extensions to specific loaders to extend Turbopack functionality. Rules are evaluated in the order they are defined.
```js
module.exports = {
turbopack: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
}
```
```js
module.exports = {
turbopack: {
rules: {
'*.svg': {
loaders: [
{
loader: '@svgr/webpack',
options: {
icon: true,
},
},
],
as: '*.js',
},
},
},
}
```
--------------------------------
### Configure custom resolve extensions
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack
Define the list of file extensions Turbopack should resolve by default in next.config.js.
```js
module.exports = {
turbopack: {
resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.mjs', '.json'],
},
}
```
--------------------------------
### Configure TypeScript options in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/typescript
Basic configuration for TypeScript settings including build error handling and custom tsconfig path.
```javascript
module.exports = {
typescript: {
ignoreBuildErrors: false,
tsconfigPath: 'tsconfig.json',
},
}
```
--------------------------------
### Dynamic deploymentId Configuration
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/deploymentId
Use environment variables like build versions or Git SHAs to dynamically set the deployment ID in next.config.js.
```javascript
module.exports = {
deploymentId: process.env.DEPLOYMENT_VERSION || process.env.GIT_SHA,
}
```
--------------------------------
### Set outputHashSalt via environment variable
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/outputHashSalt
Use the NEXT_HASH_SALT environment variable during the build process to define or extend the salt value.
```bash
NEXT_HASH_SALT=my-deployment-salt next build
```
--------------------------------
### Import Static Images from URLs
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/urlImports
Use external image URLs with the Next.js Image component.
```js
import Image from 'next/image'
import logo from 'https://example.com/assets/logo.png'
export default () => (
)
```
--------------------------------
### Enable webVitalsAttribution in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/webVitalsAttribution
Enable attribution for specific Web Vitals metrics by adding the webVitalsAttribution array to the experimental section of your next.config.js file.
```js
module.exports = {
experimental: {
webVitalsAttribution: ['CLS', 'LCP'],
},
}
```
--------------------------------
### Manual parameter mapping in destination
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites
Manually include parameters in the destination query string when they are already used in the destination path.
```javascript
module.exports = {
rewrites() {
return [
{
source: '/:first/:second',
destination: '/:first?second=:second',
// Since the :first parameter is used in the destination the :second parameter
// will not automatically be added in the query although we can manually add it
// as shown above
},
]
},
}
```
--------------------------------
### Conditional Rewrites Configuration
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites
Demonstrates how to use 'has' and 'missing' arrays to conditionally apply rewrites based on request headers, cookies, query parameters, or host values.
```javascript
module.exports = {
rewrites() {
return [
// if the header `x-rewrite-me` is present,
// this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-rewrite-me',
},
],
destination: '/another-page',
},
// if the header `x-rewrite-me` is not present,
// this rewrite will be applied
{
source: '/:path*',
missing: [
{
type: 'header',
key: 'x-rewrite-me',
},
],
destination: '/another-page',
},
// if the source, query, and cookie are matched,
// this rewrite will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the
// destination since value is provided and doesn't
// use a named capture group e.g. (?home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
destination: '/:path*/home',
},
// if the header `x-authorized` is present and
// contains a matching value, this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-authorized',
value: '(?yes|true)',
},
],
destination: '/home?authorized=:authorized',
},
// if the host is `example.com`,
// this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'host',
value: 'example.com',
},
],
destination: '/another-page',
},
]
},
}
```
--------------------------------
### Redirect with path parameters
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
Use path parameters to dynamically redirect requests while preserving query strings.
```js
{
source: '/old-blog/:path*',
destination: '/blog/:path*',
permanent: false
}
```
--------------------------------
### Enable the Rust React Compiler in next.config
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackRustReactCompiler
Configure the experimental Rust compiler in your Next.js configuration file. This requires the reactCompiler option to be enabled and is only supported when using Turbopack.
```ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
// Enable the React Compiler
reactCompiler: true,
experimental: {
// Use the Rust port instead of the Babel transform
turbopackRustReactCompiler: true,
},
}
export default nextConfig
```
```js
/** @type {import('next').NextConfig} */
const nextConfig = {
// Enable the React Compiler
reactCompiler: true,
experimental: {
// Use the Rust port instead of the Babel transform
turbopackRustReactCompiler: true,
},
}
module.exports = nextConfig
```
--------------------------------
### Enable mdxRs in next.config.js
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/mdxRs
Configure the experimental mdxRs flag within the next.config.js file to utilize the Rust compiler for MDX files.
```javascript
const withMDX = require('@next/mdx')()
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['ts', 'tsx', 'mdx'],
experimental: {
mdxRs: true,
},
}
module.exports = withMDX(nextConfig)
```