next.config.js
Next.js は、プロジェクトディレクトリのルート(例えば package.json
と同じ階層)にある next.config.js
ファイルを通じて設定できます。デフォルトエクスポートを使用します。
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
/* ここに設定オプションを記述 */
}
module.exports = nextConfig
ECMAScript モジュール
next.config.js
は通常のNode.jsモジュールであり、JSONファイルではありません。Next.jsのサーバーとビルドフェーズで使用され、ブラウザのビルドには含まれません。
ECMAScriptモジュールが必要な場合は、next.config.mjs
を使用できます:
// @ts-check
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* ここに設定オプションを記述 */
}
export default nextConfig
知っておくと良い:
.cjs
、.cts
、.mts
拡張子のnext.config
は現在サポートされていません。
関数としての設定
関数を使用することも可能です:
// @ts-check
export default (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* ここに設定オプションを記述 */
}
return nextConfig
}
非同期設定
Next.js 12.1.0以降では、非同期関数を使用できます:
// @ts-check
module.exports = async (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* ここに設定オプションを記述 */
}
return nextConfig
}
フェーズ
phase
は設定が読み込まれる現在のコンテキストです。利用可能なフェーズを確認できます。フェーズは next/constants
からインポート可能です:
// @ts-check
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
module.exports = (phase, { defaultConfig }) => {
if (phase === PHASE_DEVELOPMENT_SERVER) {
return {
/* 開発専用の設定オプションをここに記述 */
}
}
return {
/* 開発フェーズ以外の全フェーズ向け設定オプションをここに記述 */
}
}
TypeScript
プロジェクトでTypeScriptを使用している場合、next.config.ts
を使用して設定ファイル内でTypeScriptを利用できます:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
/* ここに設定オプションを記述 */
}
export default nextConfig
コメント行は next.config.js
で許可されている設定を記述する場所で、このファイルで定義されています。
ただし、どの設定も必須ではなく、各設定の機能を理解する必要はありません。代わりに、このセクションで有効化または変更したい機能を検索すると、必要な手順が表示されます。
ターゲットのNode.jsバージョンで利用できない新しいJavaScript機能は使用しないでください。
next.config.js
はWebpackやBabelによってパースされません。
このページでは利用可能なすべての設定オプションを文書化しています:
ユニットテスト(実験的機能)
Next.js 15.1以降、next/experimental/testing/server
パッケージには next.config.js
ファイルのユニットテストを支援するユーティリティが含まれています。
unstable_getResponseFromNextConfig
関数は、next.config.js
の headers
、redirects
、rewrites
関数を指定されたリクエスト情報で実行し、ルーティング結果を含む NextResponse
を返します。
unstable_getResponseFromNextConfig
からのレスポンスはnext.config.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')