env
Next.js 9.4 출시 이후, 이제 환경 변수 추가에 대해 더 직관적이고 편리하게 추가할 수 있습니다. 한번 사용해 보세요!
알아두면 좋은 점: 이 방식으로 지정된 환경 변수는 항상 JavaScript 번들에 포함됩니다. 환경 변수 이름 앞에
NEXT_PUBLIC_
을 붙이는 것은 환경 또는 .env 파일을 통해 지정할 때만 영향을 미칩니다.
JavaScript 번들에 환경 변수를 추가하려면 next.config.js
를 열고 env
설정을 추가하세요:
next.config.js
module.exports = {
env: {
customKey: "my-value",
},
};
이제 코드에서 process.env.customKey
에 접근할 수 있습니다. 예를 들어:
function Page() {
return <h1>The value of customKey is: {process.env.customKey}</h1>;
}
export default Page;
Next.js는 빌드 시 process.env.customKey
를 'my-value'
로 대체할 것입니다. webpack DefinePlugin의 특성으로 인해 process.env
변수를 구조 분해하려고 하면 작동하지 않습니다.
예를 들어, 다음 줄은:
return <h1>The value of customKey is: {process.env.customKey}</h1>;
다음과 같이 변환됩니다:
return <h1>The value of customKey is: {"my-value"}</h1>;