Next.js & dotenv
Why
To have the same .env
available in both, client and server side? We will be doing that with the help of Webpack.
Install
You need dotenv
and dotenv-webpack
.
# With yarn
yarn add dotenv
yarn add dotenv-webpack
# Or; with npm
npm install dotenv --save
npm install dotenv-webpack --save
Setup
This goes in next.config.js
at the project root.
require('dotenv').config()
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
webpack: (config) => {
config.plugins = config.plugins || []
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true
})
]
return config
}
}
The first line is to discover the dotenv config for the server-side.
Then we use dotenv-webpack
to replace those process.env.YOUR_VARS
for the client-side.
And that's it!
Subscribe to RECodes
Get the latest posts delivered right to your inbox