[Next.js]: Using environment(env) variables in Next.js
Next.js
05/11/2020
Overview
This post will show you how to set up env variables in Next.js dynamically. i.e. Using .env.development
on development and .env.production
on production.
.env
Create .env.development
and .env.production
for client side
/.env.development
TEXT
FETCH_URL=http://localhost:3000
/.env.production
TEXT
FETCH_URL=https://your-website.com
Install dotenv-webpack
BASH
npm i dotenv-webpack
next.config.js
Depending on how NODE_ENV is configured, your app will use .env.development
or .env.production
. Be sure to restart the server after changes.
/next.config.js
JS
const Dotenv = require("dotenv-webpack")
const nextConfig = { webpack: config => { config.plugins.push( new Dotenv({ path: `./.env.${ process.env.NODE_ENV === "production" ? "production" : "development" }`, }) ) return config },}
module.exports = nextConfig
For example, you can define NODE_ENV
as production inside package.son
.
JSON
{ "scripts": { "dev": "nodemon -w _server _server/server.js", "start": "NODE_ENV=production node _server/server.js", "build": "next build" }, "dependencies": { // ... }}