Published: April 18 2023

Next.js - Access Environment Variables from dotenv (.env)

This is a quick tutorial on how to create and access environment variables in Next.js with a dotenv (.env) file.

Next.js apps built with Create Next App support dotenv environment variables out of the box, so all you need to do is add a .env file to the root folder of your Next.js project.

To generate a Next.js project with Create Next App run the command npx create-next-app@latest, the tool is also used to build and serve the application. For more info about Create Next App see https://nextjs.org/docs/api-reference/create-next-app.


How to make env variables accessible to the Next.js (React) client app

There's only one gotcha, to access environment variables from the client app they must be prefixed with NEXT_PUBLIC_. Otherwise they will only be accessible on the server side.

You can access environment variables (with the NEXT_PUBLIC_ prefix) from your Next.js (React) client app via the Node.js process.env. object. For example const myVar = process.env.NEXT_PUBLIC_MY_VAR;.


Next.js env variable example on StackBlitz

Here's an example Next.js app that contains a couple of environment variables. It shows that the env variable prefixed with NEXT_PUBLIC_ is accessible directly in the Home component and the server side only variable is accessible in Next.js functions that are executed on the server (getServerSideProps() or getStaticProps()).

(See on StackBlitz at https://stackblitz.com/edit/nextjs-access-environment-variables-from-dotenv)

 

Example dotenv (.env) file

The dotenv file from the example app. It defines two environment variables, the one prefixed with NEXT_PUBLIC_ is accessible to the Next.js (React) client app, and the one without the prefix is only accessible to server side code.

# variables prefixed with NEXT_PUBLIC_ are accessible from the nextjs (react) client app
NEXT_PUBLIC_MY_ENV_VARIABLE=environemnt variable value from .env file

# variables without the NEXT_PUBLIC_ prefix are NOT accessible from the nextjs (react) client app
SERVER_SIDE_ONLY_VAR=this can't be accessed directly on the client
 

Next.js Home Component

The Home component displays the public environment variable directly from the client side code ({process.env.NEXT_PUBLIC_MY_ENV_VARIABLE}).

The Next.js functions getServerSideProps() and getStaticProps() are executed on the server so they have access to the server side environment variable (process.env.SERVER_SIDE_ONLY_VAR).

It accesses variables in the .env file with the Node.js object process.env.

export default Home;

function Home() {
    return (
        <div className="card m-3">
            <h5 className="card-header">Next.js - Access Environment Variables from dotenv (.env)</h5>
            <div className="card-body">
                <p>NEXT_PUBLIC_MY_ENV_VARIABLE: {process.env.NEXT_PUBLIC_MY_ENV_VARIABLE}</p>
            </div>
        </div>
    );
}

export async function getServerSideProps() {
    // server side env vars can be accessed in getServerSideProps() or
    // getStaticProps() because they are executed on the server    
    const myVar = process.env.SERVER_SIDE_ONLY_VAR;
    console.log('SERVER_SIDE_ONLY_VAR:', myVar);
  
    return {
        props: {}, // will be passed to the page component as props
    }
}
 

Possible hydration failed error if server side env var accessed in client code

Attempting to access an server side environment variable (without the prefix NEXT_PUBLIC_) directly on the client may result in the following error:

Error: Hydration failed because the initial UI does not match what was rendered on the server.


It's caused by the server side rendered (SSR) output not matching the initial client side code, because the environment variable is accessible on the server but not the client.

For more info on using environment variables in a Next.js app built with Create Next App see https://nextjs.org/docs/basic-features/environment-variables.

 


Need Some NextJS Help?

Search fiverr for freelance NextJS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by