Cristian Flórez
Cristian Flórez

Reputation: 2771

How to handle different .env files in Next?

What I want

I have created a new Next project, and I want to manage app behavior according to the NODE_ENV variable. The application must load different variables located in different .env files. eje. if I load NODE_ENV=development, the application should to load the variables located in .env.development file. What is the most efficient and safe way to do it in Next.

What I have

package.json

In the dev script I pass the environment type:

"scripts": {
    "dev": "cross-env NODE_ENV=development next",
    "build": "next build",
    "start": "next start",
  },

next.config.js

In the next configuration I load environment variables from correct .env file with dotenv library according to NODE_ENV variable pass in devscript in package.json.

const path = require('path');
const withOffline = require('next-offline');
const webpack = require('webpack');

require('dotenv').config({
  path: path.resolve(
    __dirname,
    `.env.${process.env.NODE_ENV}`,
  ),
});

module.exports = withOffline({
  webpack: (config) => {
    // Returns environment variables as an object
    const env = Object.keys(process.env).reduce((acc, curr) => {
      acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
      return acc;
    }, {});

    // Allows you to create global constants which can be configured
    // at compile time, which in our case is our environment variables
    config.plugins.push(new webpack.DefinePlugin(env));
    return config;
  },
});

.env.development

TITLE=modo development

pages/index.js

function HomePage() {
  return <div>{process.env.TITLE}</div>
}

export default HomePage

With this aproach...

Upvotes: 2

Views: 7122

Answers (2)

Syed Muhammad Ahmad
Syed Muhammad Ahmad

Reputation: 438

Agree with the @felixmosh that Nextjs supports env by default without the need to use of webpack.DefinePlugin, but...
It may be seen as limited and confused while loading different configurations on each environment. You can see common problem here enter link description here

You can solve this problem easily by following these small steps.

  1. You’ll need to create a folder config on the root, with all environment stages you’d like to have. enter image description here

  2. You can add the initial/common configuration in default.js like this.

      API: {
        API_URL: process.env.API_URL || '<http://localhost:4000>',
        ENDPOINT: '********',
        IS_MOCKING_ENABLED: false,
      },
    }```
    
    
  3. Include above config files in the Next.config.js file by publicRuntimeConfig. If you’d like to have it just on the server-side use just serverRuntimeConfig like this.

    const APIConfig = config.get('API')
    const nextConfig = {
     publicRuntimeConfig: {
      APIConfig,
     },
    }
    module.exports = nextConfig ```
    
    
  4. Usage in any file.

  5. 
    const { publicRuntimeConfig } = getConfig()
    const APIConfig = publicRuntimeConfig.APIConfig
    [...] ```
    
    
  6. Finally, in your package.json. You can inject the environment variables to load the appropriate configuration. "start:local": "NODE_ENV=development run-p dev"

  7. Reference: enter link description here for detail explanation.

Upvotes: 2

felixmosh
felixmosh

Reputation: 35473

Nextjs supports env by default without the need to use of webpack.DefinePlugin, just pass it to the env property of next.config.js.

So your code will become:

// next.conf.js
const path = require('path');
const withOffline = require('next-offline');
const webpack = require('webpack');

require('dotenv').config({
  path: path.resolve(
    __dirname,
    `.env.${process.env.NODE_ENV}`,
  ),
});

module.exports = withOffline({
  env: {
    VAR_1: process.env.VAR_1
    ...
    // List all the variables that you want to expose to the client
  }
});

PAY ATTENTION: these env variables may be exposed to the client side (if you use them in one of your app page).

For example, if your process.env is containing secrets, and by mistake you are using one of them in one of the pages / components that are used by pages, they will be inside js files that are downloaded to the client side.

Since Next.js 9.4, there is a built in .env loading functionality, read about it here https://nextjs.org/docs/basic-features/environment-variables

Upvotes: 5

Related Questions