How to use environment variables in Next.js (includes a working sample app) – News Block

Next.js is a React framework that makes it easy to build fast and easy-to-use websites. It uses server-side rendering to pre-render pages on the server, making them load faster for users. Environment variables are a way to store sensitive information, such as passwords or API keys, outside of your code. This makes it more secure, it is one of the 12 factor application tenants. In this post, you will learn how to properly use environment variables on both the server and client side of Next.js. Let us begin!

Learn how to use Next.js environment variables the easy way

Table of Contents #

Next.js# Popularity

Next.js is a fast, scalable, and easy-to-use React framework that can be used to build static, dynamic, and server-side rendered applications. It is popular for its static site generation, server-side rendering, routing, pre-rendering, and SEO features. Some of its competitors are Nuxt.js, Gatsby, and Remix.
Next.js is the most popular React.js meta framework if you look at Google search trends over the last 5 years.

Next.js is the most popular React meta framework

Next, you’ll learn about environment variables and their use in web applications.

Environment Variables #

Environment variables are a set of variables used to store information about the environment in which a web application is running. They are defined in a key-value pair. This information can include things like the path to the application’s files, the name of the database, and the port number that the application is listening on.

Environment variables are often used to configure applications, and can also be used to store data that must be accessed by various parts of an application.

Environment variables can be a powerful tool for configuring and managing web applications. By understanding how they work, you can use them to make your applications more flexible and easier to maintain. For example, below is a sample .env file used for an application’s environment variables:


With the above environment variables in a .env or as environment variables at the operating system level, you can choose whatever database you like. For example, in the staging stage, it will point to a staging database, and for a production environment, the credentials of the production database will be used.
One more thing to note above is the DB_URL which is constructed by reference to the other variables with a $ sign.

Next.js will automatically expand variables using $ to reference other variables, thus constructing a valid DB_URL replacing the correct environment variables.
In the next section, you’ll learn about Next.js environment variables.

Environment variables in Next.js#

For this post, you’ll be using Next.js 13 with the app router (not the pages folder). To use environment variables in Next.js, you can create a .env.local file in the root directory of your project. This file will contain all of your environment variables, which you can then access in your code using the process.env object while executing back-end or server-side components.
For example, if you have an environment variable called SECRET_KEY, you can access it in your code like this:

const secretKey = process.env.SECRET_KEY;

You can also use environment variables to configure different settings for your website. For example, you could create an environment variable called PRODUCTION that you set to true when your website is live. This would allow you to use different configurations for your production website than you would for your development website. You can read more about this in the official docs.

Browser level environment variables Next.js #

Sometimes you will need to expose some variables to make them accessible in the browser-level interface. Of course, these variables can’t be secret (like a password), since everyone can read them, since it’s part of the interface code.

Let’s say if you want to use Google Analytics 4, you’ll need to expose the GA4 Measurement ID in the browser.
To expose a public environment variable in Next.js, you must prefix the environment variable with NEXT_PUBLICso for the measurement ID of GA4 it can be stated as follows:


You will learn about the loading order of environment variables in Next.js in the next section.

Load order of environment variables in Next.js#

The environment variable has an order of precedence in Next.js which is as follows:

  1. process.env
  2. .env.$(NODE_ENV).local
  3. .env.local (Not checked when NODE_ENV is test).
  4. .env.$(NODE_ENV)
  5. .env

For NODE_ENV the only values ​​allowed are development, production, and test. In the case of precedence, if NODE_ENV is development and you define a variable you say DB_HOST in both .env.development.local and .envthe value in .env.development.local it will be used according to the order of precedence above.
You’ve learned about Next.js environment variables, now it’s time to put the knowledge in the next section into practice with a sample application.

City Weather App Example#

To put what you’ve learned about Next.js environment variables, you’ll clone and run a sample application that can display the temperature for a given city. The application has two parts. The first part to call and API with an API key to get the weather for a city will use a server-only environment variable.

Then the second part is to add the Google Analytics 4 script to the app that will use the public (frontend/browser) level environment variable.
The running application looks like the following:

Next.js city weather app runs on Vercel

As you can see, it’s a standard Next.js app installed with npx (email protected). It doesn’t use Typescript and Tailwind, but it does use the new app router and EsLint. To get to the previous stage, the following two Next.js environment variables have been used:


You can understand what is happening in the application by looking at the visual representation of the communication flow between the systems involved as follows:

Next.js city weather app that talks to API Ninjas API and Google Analytics

When the user accesses the URL with (or without the city), the Next.js application will send a request to API Ninjas with the API key provided (free) by API Ninjas. This app calls the Weather API from API Ninjas and sends the name of the city. If the name of the city is not given, it returns to London.

If you make the API Ninjas API key public, other people can also use and/or abuse it. That is why it is set as a Next.js environment variable at the server level. In order for your app to work, you’ll also need to sign up and get your own free API Key from API Ninjas.

Another system involved is Google Analytics. A GA4 tag is added to the weather app that will report page views to Google Analytics. You used the measurement ID to identify the application. You can follow this tutorial for a step by step process to add GA4 in a Next.js application.

The goal of this guide is to explain Next.js environment variables. Because the GA4 script runs at the browser level, the Measurement ID environment variable is set to NEXT_PUBLIC so that it can be used in the interface/browser. This environmental variable may be exposed to the public.

The app is currently deployed in Vercel, you can also use Next.js with Docker to run the app locally. With Docker you can easily run any Next.js application without having to have a specific version of Node.js or NPM. These dependencies can be configured as code in the Dockerfile.

City Weather Next.js Application Code #

The code in the stock Next.js starter template has been changed a bit to add a server call to API Ninjas and also add the Google Analytics 4 script to the page. You will need to know how Next.js works as a prerequisite. All code changes have been made in the src/app/page.js file that looks like the following:

import Image from 'next/image';
import styles from './page.module.css';
import Script from 'next/script';

async function getWeatherData(city) {
const res = await fetch(`${city}`, {
headers: {
'Content-Type': 'application/json',
'X-API-Key': process.env.API_NINJAS_API_KEY,
const data = await res.json(); = city;

return data;

export default async function Home(req) {
const city = || 'London';
const weatherData = await getWeatherData(city);
return (
<main className={styles.main}>
<div className={styles.description}>
Current temprature in {} is
<code className={styles.code}> {weatherData.temp} C</code>
rel="noopener noreferrer"
By{' '}
alt="Vercel Logo"

<div className={}>
alt="Next.js Logo"

<div className={styles.grid}></div>
<Script id="google-analytics" strategy="afterInteractive">
window.dataLayer = window.dataLayer || ();
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '

The change to this src/app/page.js are as follows:

  • He Script the label has been imported from next/script on line number 3
  • On line 4, you have also assigned the Next.js environment variable NEXT_PUBLIC_GA_MEASUREMENT_ID to a constant call GA_MEASUREMENT_ID
  • From line 6-17, the getWeatherData asynchronous function uses fetch to call the API Ninjas Weather API passing the city that is passed as a parameter to the function. Returns the data received from the API call after adding the city to it. This function runs on the server and used the API_NINJAS_API_KEY Next.js environment variable to make the API call.
  • In the Home component, city is obtained from the URL query parameter if it exists; otherwise, the city variable gets a fallback value of London on line 20.
  • On line 21, the getWeatherData The function is called with the city constant set on line 20.
  • The name of the city and the current temperature in that city are represented on lines 24-28
  • On lines 60-71, the GA4 tag that uses the Next.js public environment variable is placed twice. Once for the Google tag manager and again on line 69 for the GA setting.

With these changes, you have now used the server-side and client-side (browser) environment variable Next.js in a small but useful and functional application. All the code is available in the public GitHub repository.

You can easily deploy this app to Vercel by clicking the “Deploy” button in the readme or find it running on Vercel. You can clone/fork the repository and change it to suit your needs.

Live! You learned how to use the Next.js environment variable with the help of a sample worker app that gets live weather for any given city and sends analysis to GA 4.

Conclusion #

In this guide, you learned about Next.js and its popularity. Later, she also got some knowledge about environment variables for web applications and specifically for Next.js. After that, he learned both types of Next.js environment variables (server and client which are public) and the order of precedence to use them.

Then you saw an example of a Next.js application that extracts the current weather for any given city using server-level and client/browser-level environment variables.

I hope you have learned something new, keep absorbing more knowledge. If you have any questions or comments, please leave them below.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top