env
Since the release ofNext.js 9.4 we now have a more intuitive and ergonomic experience foradding environment variables. Give it a try!
Good to know: environment variables specified in this way willalways be included in the JavaScript bundle, prefixing the environment variable name with
NEXT_PUBLIC_only has an effect when specifying themthrough the environment or .env files.
To add environment variables to the JavaScript bundle, opennext.config.js and add theenv config:
module.exports= { env: { customKey:'my-value', },}Now you can accessprocess.env.customKey in your code. For example:
functionPage() {return <h1>The value of customKey is: {process.env.customKey}</h1>}exportdefault PageNext.js will replaceprocess.env.customKey with'my-value' at build time. Trying to destructureprocess.env variables won't work due to the nature of webpackDefinePlugin.
For example, the following line:
return <h1>The value of customKey is: {process.env.customKey}</h1>Will end up being:
return <h1>The value of customKey is: {'my-value'}</h1>Was this helpful?