DeployU
Interviews / Frontend Engineering / How do you handle environment variables in Next.js?

How do you handle environment variables in Next.js?

practical Configuration Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new Next.js application that needs to connect to a database.

You need to store the database credentials in a secure way, and you do not want to commit them to your Git repository.

The Challenge

Explain how you would handle environment variables in Next.js. What are the different ways to set environment variables, and what are the trade-offs between them?

Wrong Approach

A junior engineer might try to hardcode the database credentials in the code. This would be a very bad practice, because it would make the credentials visible to anyone who has access to the code.

Right Approach

A senior engineer would know that there are several different ways to handle environment variables in Next.js. They would be able to explain the pros and cons of each approach and would have a clear recommendation for which one to use in a given situation.

Step 1: Understand the Different Ways to Set Environment Variables

MethodDescription
.env filesA set of files that can be used to set environment variables for different environments (e.g., .env.local, .env.development, .env.production).
next.config.jsThe env property in the next.config.js file can be used to set environment variables.
now.jsonIf you are deploying your application to Vercel, you can use the now.json file to set environment variables.

Step 2: Choose the Right Tool for the Job

For our use case, we should use .env files. This is because it is the most flexible and secure way to handle environment variables.

Step 3: Code Examples

Here’s how we can use .env files to set environment variables:

.env.local:

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

pages/api/my-api.js:

export default function handler(req, res) {
  const dbHost = process.env.DB_HOST;
  // ...
}

Exposing Environment Variables to the Browser

By default, environment variables are only available on the server. If you want to expose an environment variable to the browser, you need to prefix it with NEXT_PUBLIC_.

.env.local:

NEXT_PUBLIC_MY_VAR=myvalue

pages/my-page.js:

export default function MyPage() {
  const myVar = process.env.NEXT_PUBLIC_MY_VAR;
  // ...
}

Practice Question

You want to store a secret API key that should not be exposed to the browser. Which of the following would you use?