Type to generate custom UI components with AI

Type to generate UI components from text


Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use NextJS Environment Variables: A Simple Guide

NextJS Environment Variables: Simplifying Web Development

In the world of web development, environment variables play a crucial role in customizing application behavior based on different environments. They are key-value pairs that allow developers to store sensitive data, such as API keys or database connection strings, separately from their codebase.

Next.js, a popular React framework, provides built-in support for environment variables, making it easier than ever to manage and utilize them in your applications.

In this comprehensive guide, we will explore the ins and outs of Nextjs env variables. We’ll start by explaining what environment variables are and why they are important in web development. Then, we’ll delve into the specific features and benefits that Next.js offers for working with environment variables.

By the end of this guide, you’ll have a solid understanding of how to effectively use Next js env variables to enhance the functionality and security of your applications.

So, let’s get started on our journey to master Next.js environment variables!

What are Environmental variables?

Environment variables are external configurations that can be accessed by the software during runtime. These variables store sensitive information, API keys, database connection strings, and other parameters that should not be hardcoded into the source code. This practice enhances the security, scalability, and maintainability of the application.

Significance in Next.js

Next.js leverages environment variables to provide a seamless development experience. They are particularly useful for managing API keys, controlling feature flags, and configuring application settings.

The framework offers two types of environment variables: public and private.

  1. Public Environment Variables: These are accessible to both the client and server-side code. Useful for storing non-sensitive information like API URLs.

  2. Private Environment Variables: Available only to the server-side code, these variables are ideal for storing sensitive data such as API keys and database credentials.

Refer to the official docs of next.js to learn more about the basics of environment variables in next.js

Getting Started with NextJS Environment Variables

Before we dive into the details of Next.js environment variables, let’s first set up a basic Next.js project and familiarize ourselves with the necessary directory structure.

Step 1: Make sure you have Node.js and npm (Node Package Manager) installed on your machine. You can easily find a guide online!

Step 2: Open up your terminal or command prompt and create a new directory for your project.

Step 3: Navigate into the newly created directory and run the following command to initialize a new Next.js project:

npx create-next-app my-app

This command will set up a new Next.js project in a folder named “my-app”.

Step 4: Once the initialization is complete, navigate into the “my-app” directory:

cd my-app

Now that we have our basic Next.js project set up, let’s move on to working with environment variables. In Next.js, environment variables are loaded from a file called .env.local, which should be placed in the root directory of your project.

Step 5: Create a new file named .env.local in the root directory of your project. This file will contain the key-value pairs for your environment variables.

For example, let’s define an environment variable called API_URL with the value ‘<https://api.example.com>’.

Step 6: Open the .env.local file and add the following line:


Continue to add any other environment variables you need for your application, each on a new line in the .env.local file.

Now that we have defined our environment variables, we can access them in our Next.js application using the process.env object.

Next, we’ll explore how to use these environment variables in different parts of a Next.js application.

Exploring Next.js Environment Variables

To harness the power of Next.js fully, it’s essential to understand the various environment variables at your disposal. These variables play a crucial role in configuring your application, managing secrets, and controlling feature toggles.

Let’s explore the key environment variables in Next.js and their significance.

Next.js Environment Variables Table

Variable Name Scope Description NEXT_PUBLIC_API_URL Public (Client) URL for accessing public APIs API_SECRET_KEY Private (Server) Secret key for server-side operations FEATURE_TOGGLE_ENABLED Public (Client) Toggle to enable or disable specific application features NEXT_PUBLIC_APP_TITLE Public (Client) Title of the application shown in the header NEXT_PUBLIC_API_KEY Public (Client) API key for accessing external services

These variables provide a flexible way to manage configurations, ensuring that sensitive information is secure while allowing for dynamic adjustments based on your application’s requirements.

Using Environment Variables in Next.js Applications

A. Accessing Environment Variables in Server-side Code

  • In Next.js, server-side code refers to code that is executed on the server before sending the response to the client. This includes functions like getStaticProps and getServerSideProps.

  • To access environment variables in server-side code, we can simply use the process.env object.

  • For example, let’s say we have an environment variable called API_KEY that stores our API key for making requests to an external API.

  • For example, let’s try to access information about India through countries API endpoint whose url we have stored as an environment variable

// .env.local

// /pages/api/countries.js api route

import axios from 'axios'

export default async (req, res) => {
	try {
		// Use the REST Countries API to get information about India
		const response = await axios.get(`${process.env.API_URL}`)

		// Extract relevant information
		const indiaInfo = response.data[1]

		// Assuming the response has 'subregion' and 'capital' fields
		const state = {
			state: indiaInfo.name.common,
			subregion: indiaInfo.subregion,
			capital: indiaInfo.capital[0]
	} catch (error) {
		res.status(500).json({ error: 'Internal Server Error' })

In this example, we are using the API_URL one environment variables to construct the URL for our API request.

By utilizing environment variables, we can easily modify the behavior of our Next.js application based on the specific environment it is running in.

B. Making Environment Variables Available in Browser-side Code

  • Next.js treats environment variables as private by default, meaning they are only accessible in the Node.js environment on the server.

  • However, there are cases where we may need to access these variables in client-side JavaScript code.

  • To make an environment variable accessible in the browser, we need to prefix it with NEXT_PUBLIC_.

  • For example, let’s say we have an environment variable called API_KEY that stores our API key.

  • To make this variable available in client-side code, we can define it as follows in our .env.local file:

  1. Create a .env.local File: Create a file named .env.local in the root of your Next.js project.


  2. Access Environment Variable in Browser-side Code: In your React component or page file, you can directly access this environment variable in the browser-side code.

    // pages/index.js
    const apiKey = process.env.NEXT_PUBLIC_API_KEY;
    const HomePage = () => {
      return (
          <p>Your API Key: {apiKey}</p>
    export default HomePage;

In this example,

  • The NEXT_PUBLIC_API_KEY environment variable is accessed directly in the index.js page component.

  • When the page renders on the client side (in the browser), it will display the API key dynamically.

  • This way, sensitive information like API keys can be securely stored in environment variables and accessed on the client side as needed.

By making this environment variable public, we ensure that it is accessible in the browser.

C. Referencing Other Environment Variables within .env.local

  • Next.js provides a useful feature that allows us to reference other environment variables within the .env.local file itself. This can be handy when we want to reuse the value of one variable in another.

  • To reference another environment variable within the .env.local file, we can use the $ syntax.

  • Let’s consider an example where we have a base URL and an API endpoint

  • We can define a variable called BASE_URL and reference it within API_ENDPOINT as follows:


In this case, the value of process.env.API_ENDPOINT will evaluate to <‘https://restcountries.com/v3.1/name/india?fields=name,subregion,capital’>. This makes it easier to create dynamic URLs or paths based on other environment variables.

Follow this video tutorial for detailed information on using environment variables in your next JS applications

Differentiating Environments with Next.js

A. Environment-specific Configuration Files

  • Having separate configuration files for different environments is a common practice in web development.

  • Next.js allows us to define environment variables specific to different environments by using separate configuration files.

  • For example, we can create a .env.development file for our development environment and a .env.production file for our production environment. The variables defined in these files will only be available in their corresponding environments.

  • To define environment variables for the development environment, create a file named .env.development and add your variables there. Similarly, create a file named .env.production for your production environment.

Let’s say we have a variable called API_KEY that needs a different value in the development and production environments.

We can define this variable in the respective environment files as follows:



By separating environment-specific variables into different files, we can easily customize the behavior of our Next.js application based on the environment it is running in.

B. Customizing Behavior with next.config.js

In addition to using separate configuration files for different environments, Next.js provides the next.config.js file to further customize the behavior of our applications based on environment variables.

To define environment variables using next.config.js, export an object from this file with an env property that contains your variables. For example:

// pages/index.js
const apiKey = process.env.NEXT_PUBLIC_API_KEY;

const HomePage = () => {
  return (
      <p>Your API Key: {apiKey}</p>

export default HomePage;
// next.config.js
module.exports = {
  env: {

With this configuration, we can access the BASE_URL environment variable in our code using process.env.BASE_URL.

The next.config.js file allows us to define additional settings and behaviors for our Next.js application, not just limited to environment variables. It is a powerful tool for customizing various aspects of our application’s build process.

C. Securely Storing Secrets in env. local

  • When working with environment variables, it is crucial to securely store any sensitive information, such as API keys or database connection strings.

  • In Next.js, we can achieve this by adding the .env.local file to our .gitignore file.

  • By adding the .env.local file to .gitignore, we ensure that it is not committed to version control systems like Git. Instead, we provide a template file (e.g., env.local.template) that project contributors can use to set up their local development environment.

  • This approach allows each developer to create their version of the .env.local file with their specific environment variables, without exposing sensitive information to version control systems.

Here is a link to a detailed article by bymoji.com on differentiating environments with next js.

Now that we know the different features NextJS environment variables have in store for us. Dive into your projects, implement environment variables, and experience the newfound flexibility and security they bring to your applications.

Along with that don’t forget to supercharge your front-end development withPureCode.ai. Transform design images into ready-to-use code, explore over 10,000 AI-generated custom components, and effortlessly apply custom themes to Tailwind, MUI, and CSS3.

Advanced Next.js Environment Variable Techniques

A. Dynamic Environment Variables at Runtime

  • Next.js evaluates environment variables at build time, which means that any dynamic lookups or destructuring of environment variables in the frontend code will not work.

  • This limitation is important to consider when working with Next.js environment variables.

  • If you need access to dynamic environment variables at runtime, one possible solution is to set up your API to provide the variables to the client. This way, you can fetch the values of the environment variables from your API and use them in your client-side code.

  • For example, you can create an endpoint on your server that returns the values of the environment variables as JSON. Then, in your Next.js application, you can fetch this JSON from your server and use the received values as dynamic environment variables at runtime.

B. Environment Variable Hierarchy in Next.js

Next.js follows a specific hierarchy when looking up environment variables. The order of lookup is as follows:

  1. process.env

  2. .env.$(NODE_ENV).local

  3. .env.local

  4. .env.$(NODE_ENV)

  5. .env

The value of NODE_ENV is determined by the current environment. For example, in a development environment, it is set to development. In a production environment, it is set to production. In a test environment, it is set to test.

This hierarchy allows us to define different sets of environment variables depending on the environment in which our Next.js application is running.

Follow this video tutorial to learn more about advanced next-environment variable techniques

Practical Implementation: Feature Toggle

Let’s explore a practical implementation of Next.js environment variables by creating a feature toggle.

This allows you to enable or disable specific features without changing the codebase.

  1. Create a Feature Toggle Variable:


  2. Implement Feature Toggle in Code:

    // pages/index.js
    const featureToggleEnabled = process.env.FEATURE_TOGGLE_ENABLED === 'true';
    const HomePage = () => {
      return (
          {featureToggleEnabled ? (
            <p>Feature is Enabled! 🚀</p>
          ) : (
            <p>Feature is Disabled. 😔</p>
    export default HomePage;

In this example, the FEATURE_TOGGLE_ENABLED environment variable is used to conditionally render a feature on the homepage. This allows you to control the feature’s visibility without modifying the code.

Best Practices for Using Next.js Environment Variables

To make the most out of Next.js environment variables, it’s important to follow some best practices:

  1. Use descriptive names: Choose meaningful names for your environment variables that convey their purpose. This makes it easier for other developers to understand their functionality.

  2. Organize your .env.local file: Group related variables together in your .env.local file for better readability and organization. This can help you quickly locate and update specific variables as needed.

  3. Regularly review and update your environment variables: As your application evolves, it’s important to periodically review and update your environment variables. This ensures that they are up-to-date with any changes in your application’s requirements or dependencies.

Refer to this blog on medium.com for more such best practices to follow for using next.js environment variables

By following these best practices, you can maintain a clean and efficient environment variable setup in your Next.js applications.

Mastering Next.js Environment Variables for Enhanced Development

In our exploration of Next.js environment variables, we’ve uncovered a powerful tool for configuring applications securely and efficiently. As we conclude our journey, let’s recap the key takeaways and set the stage for your next steps.

Key Takeaways:

  • Significance of Environment Variables: Next.js leverages environment variables to enhance security, scalability, and maintainability.

  • Practical Implementation: We demonstrated a practical use case with a feature toggle, showcasing how environment variables empower dynamic feature control without modifying the codebase.

  • Best Practices: Descriptive naming, encryption of sensitive data, and providing default values contribute to a smooth and secure development process.

Elevate Your Development Workflow:

Ready to put your newfound knowledge into action? Here’s your call to action:

Try It Yourself:

  1. Explore Next.js Environment Variables: Dive into your projects, implement environment variables, and experience the flexibility they bring to your applications.
  2. Experience PureCode.ai: Take your front-end development to the next level with PureCode.ai. Transform design images into ready-to-use code, explore over 10,000 AI-generated custom components, and effortlessly apply custom themes to Tailwind, MUI, and CSS3.

Happy coding!

Yash Poojari

Yash Poojari