Is it possible to add .env variables to a Next.js app?
I think the only way possible is thru a webpack plugin...
Would be awesome if it did work the same way as CRA:
https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables
Exposing variables prefixed with NEXT_ would be awesome!
If there is some interest i would be happy to look into it and make a PR if I find a good solution.
Check this https://github.com/zeit/next.js/tree/canary/examples/with-universal-configuration
You can add your .env and with require('dotenv').config() load them in process.env, then inside env-config.js pass what you need from process.env to your Next.js app.
Ah, nice. Thanks 馃憤
is env-config.js secret? @sergiodxa
Why isn't env-config.js documented? Why not to simply update webpack config with env variables at next.config.js?
env-config.js is not something in Next.js. It鈥檚 part of babel plugin transform define in the example. Check the .babelrc. 7 months ago next.js didn鈥檛 have universal webpack yet, so you couldn鈥檛 use defineplugin
@sergiodxa
In env-config.js one can differentiate between dev and production variable by process.env.NODE_ENV === 'production'. What if someone want to create separate env variables for
I have this requirement.
@vaibhavi3t You can use dotenv or some other way of loading up env variables and then just export them. All this does is when babel is transforming your code during the build process it replaces the keys with the given value.
// env-config.js
require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' })
module.exports = {
'process.env.SOME_ENV_VAR': process.env.SOME_ENV_VAR,
'process.env.SOME_OTHER_VAR': process.env.SOME_OTHER_VAR
};
Updated link that @sergiodxa pointed out >> https://github.com/zeit/next.js/tree/canary/examples/with-universal-configuration-build-time
https://github.com/zeit/next.js/tree/canary/examples/with-universal-configuration is broken, what to do?
Most helpful comment
Check this https://github.com/zeit/next.js/tree/canary/examples/with-universal-configuration
You can add your
.envand withrequire('dotenv').config()load them inprocess.env, then insideenv-config.jspass what you need fromprocess.envto your Next.js app.