/ javascript

Next.js & dotenv


To have the same .env available in both, client and server side? We will be doing that with the help of Webpack.


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


This goes in next.config.js at the project root.


const path = require('path')                                                      
const Dotenv = require('dotenv-webpack')                                          

module.exports = {                                                                
  webpack: (config) => {                                                          
    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!