is coming soon...
ado.xyz

How to Work With Environment Variables in Next.js

February 23, 2021

Environment variables are a developers best friend. Environment variables have many use cases, like ensuring you don’t hard code sensitive API keys and commit them to a public GitHub repo (oops!), and today we’ll learn how to get the most out of them with Next.js .

Environment variables exist outside of your application and are typically loaded in when the application is built or deployed. You will typically have different configurations for your development, testing, and production environments, and Next.js makes it very intuitive to set up different configurations for the different environments.

Prefer video explanation instead? Here you go:

Setting Up Environment Variables in Next.js

The easiest way to get started with environment variables in Next.js is to create a .env.local file at the root of your Next.js project. In this file, you will define key-value pairs for your environment variables.

Say for example your application relied on a SaaS platform like Twilio and instead of hard-coding the secret Twilio SID and AUTH_TOKEN keys, it would make more sense to set it as an environment variable. You can have any number of key-value pairs in your .env.local file and they can represent anything, not just API keys.

As for the syntax for this file, the left hand text will be the key, followed by an = and then the value you want to represent. Traditionally, environment variable keys are types in ALL CAPS, but it’s not a requirement. Here’s what a .env.local file may look like:

//.env.local

TWILIO_ACCOUNT_SID=12345
TWILIO_AUTH_TOKEN=akdfh123h2jkhhds23
AUTH0_API_KEY=agkasd2398sakja2u98s
MONGO_DB_HOST=localhost
MONGO_DB_USER=ado
MONGO_DB_PASS=letmein123
FAVORITE_ANIMAL=bird

Accessing Environment Variables in Next.js

Now that we know how to create our environment specific configuration file, let’s learn how to load it and use it. With Next.js, it couldn’t be simpler. When you start your application, if a .env.local file exists, Next.js will load it automatically for you and let you know in the terminal by logging a message that says “Loaded env from {YOUR-PROJECT-ROOT/.env.local}”.

So the loading of our environment variables is taken care of by the framework. Let’s see how we can access these variables in our application next.

Since environment variables typically contain sensitive information that we normally wouldn’t want to expose to the end user or the browser, where we can access our environment variables from will be limited.

Our environment variables above are limited to server-side environment of the Next.js framework. This means that we can access the environment variables in our data fetching methods getStaticProps(), getServerSideProps(), getStaticPaths(), as well as our API routes . To access any of our .env.local variables, we’d use the global process.env object and pass the variable we want to access. For example:

export async function getStaticProps() {
  const accountSid = process.env.TWILIO_ACCOUNT_SID
  const authToken = process.env.TWILIO_AUTH_TOKEN
  const client = require('twilio')(accountSid, authToken)

  client.messages
    .create({
      body: 'Is this thing on?',
      from: '+15559876543',
      to: '+15551234567',
    })
    .then((message) => console.log(message.sid))
}

But what if we wanted to expose our environment variables to our entire Next.js application? We can do that as well!

Access Public Environment Variables in Next.js

Sometimes, we’ll want to set an environment variable that doesn’t need to remain a secret or one that will be consumed by the browser.If we want to expose a specific environment variable to both our browser and the server-side environment all we need to do is prepend our variable key with NEXT_PUBLIC_.

Let’s see how this works with a concrete example. Let’s say we wanted to add a Google Analytics tracking code to our Next.js application. This code is ideally going to be different across the different environments we have, so it makes sense to store it as an environment specific variable, but we also want this to be loaded by the browser. We’ll update our .env.local file accordingly:

//.env.local

TWILIO_ACCOUNT_SID=12345
TWILIO_AUTH_TOKEN=akdfh123h2jkhhds23
AUTH0_API_KEY=agkasd2398sakja2u98s
MONGO_DB_HOST=localhost
MONGO_DB_USER=ado
MONGO_DB_PASS=letmein123
FAVORITE_ANIMAL=bird
NEXT_PUBLIC_GA_TRACKING=ga-123456-f

By adding NEXT_PUBLIC_ to our key GA_TRACKING key, we’ll be able to access the value both in our server-side and browser environments. So we can go into our React component and access the value:

function HomePage() {
  console.log(process.env.NEXT_PUBLIC_GA_TRACKING) //ga-123456-f
  return <div>Welcome to Next.js!</div>
}

export default HomePage

And if we needed the value in our server-side environment with say getServerSideProps(), we would do:

export async function getServerSideProps() {
  console.log(process.env.NEXT_PUBLIC_GA_TRACKING) //ga-123456-f
}

Summary

Working with environment variables in Next.js is very intuitive. The power to load environment variables both server-side and browser side when needed provides great flexibility for developers. Typically, you’d only have a single .env.local file that holds sensitive data, but if you need general config variables, you could create an accompanying .env.development and .env.production files as well that behave much the same way. For additional information, check out the Next.js environment variables docs page .

Happy hacking.

Newsletter

Subscribe to the newsletter and be the first to know when I publish new content. No Spam.