kyun
kyun

Reputation: 10294

.env with next.js on local

I have 2 files about .env

.env.local

STAGE=local
API=http://localhost:3333

.env.dev

STAGE=dev
API=https://dev.api.domain.com

I want to seperate them as package.json's script

What I want

"script": {
    "start-local": ".env.local && next",
    "start-dev": ".env.dev && next"
}

Upvotes: 0

Views: 915

Answers (1)

felixmosh
felixmosh

Reputation: 35573

You can load a specific .env file by some env variable.

For example:

"script": {
    "start-local": "NODE_ENV=local next",
    "start-dev": "NODE_ENV=dev next"
}

This will define the NODE_ENV environment variable, then based on it, you can use dotenv lib to load the proper file.

// next.config.js
const dotEnv = require('dotenv');
const path = require('path');

const envFilePath = path.join(__dirname, `.env.${process.env.NODE_ENV}`); // this will have the path to the proper `.env` file

dotEnv.config({ path: envFilePath }); 

module.exports = {
  ...
} 

Upvotes: 1

Related Questions