Using Environment Variables on the Front-end with NextJS

A common usecase you may have in your web app is sharing some environment variables between your server-side and client-side code.

Hopefully, you are already following best practices and have these environment variables stored inside a .env file:

HOST=https://myapp.com
APP_ID=my-new-app
REST_API_ENDPOINT=https://myapp.com/api

On the server, you can use the dotenv npm module to read your .env file and put all the information in process.env.

const dotenv = require('dotenv');
dotenv.config();
console.log(process.env)

/*
Console log: { HOST: "https://myapp.com", APP_ID: "my-new-app", REST_API_ENDPOINT: "https://myapp.com/api" } 
*/

You can’t use dotenv on the client because it has a dependency on the file-system. If you aren’t using NextJS, you will have to update your Webpack config to inject the environment variables so they are available globally.

However, if you are using NextJS, there is a simpler way. You can add the environment variables to your next.config.js file:

module.exports = {
  publicRuntimeConfig: {
    appId: process.env.APP_ID,
    host: process.env.HOST,
    restAPIKey: process.env.REST_API_KEY,
  },
};

Then, you can call these variables from some client-side code:

import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();

// Here, publicRuntimeConfig contains appId, host, restApiKey

export default publicRuntimeConfig;

This is an easy way to:

  • Keep all your environment variables in one place (your .env file),
  • Explicitly specify which of them should be exposed to the client
  • Not fiddle with Webpack config (who enjoys doing that?)

PS: If you are using Create React App on the frontend, there’s an even simpler way. You can prefix all your variables inside the .env file with REACT_APP.

Up Next:

How to have effective 1-on-1 meetings

How to have effective 1-on-1 meetings