A drawn image of Fredrik Bergqvist in a blue shirt

Fredrik Bergqvist

Web developer with over 22 years of experience. Writing about javascript and front end techniques

Quick tip: .env in next.js

Using environment variables is a great way to store environment specific values and secrets that should not be in the git repo.

Lets say you have an API which runs on localhost locally but a different host in production.

On the server

Locally you need to add an .env.local-file in your project root containing a variable for the api host name, lets call it API_HOST and point it to localhost port 8080.

# .env.local in project root
API_HOST=http://localhost:8080

You would then need to add the environment variable to your production env as well. This will look different depending on your hosting provider but on Google Cloud Run it looks like this:

On the client

To expose your environment values to the client, you need to add them to your next.config.js

In most cases keeping using the variable on the server is enough, but in some cases you might need to access the environment variable on the client as well and in those cases you need to add the variable to your next.config.

// next.config.js
module.exports = {
  env: {
    API_HOST: process.env.API_HOST
  }
}