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
Good to know: 拡張子が
.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を使用している場合、設定にTypeScriptを使用するためにnext.config.tsを使用できます:
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')