Client-side environment variables with Next.js

Next.js does a great job with environment variables. Out of the box, it supports loading up environment variables in next.config.js as well as using a .env file. Both of which are made available inside of server components.

For client-side components though, you don’t get direct access to environment variables from both locations.

The Next.js config

Personally, I don’t really mess with the Next.js config file, next.config.js. While it’s a great idea, I would prefer to keep my environment variables out of there. Since environment variables tend to be sensitive, I like to utilize a .env file which remains outside of version control.

Some of what I’m about to talk about for the .env will also apply to next.config.js, but I’m not going to encourage that.

The dot-env file

Yes, when referring to the .env file, I do explicitly say “dot-env”. It’s why I say “a .env file” and not “an .env file”. Going to show my age a bit, but this bit of my vernacular came from a book I read in high school, Masters of Deception: The Gang That Ruled Cyberspace. They had a script, “dot-annoy” or .annoy that would… annoy their target. The naming always stuck, so I always pronounce the dot.

Back to business, as mentioned, the .env file doesn’t automatically expose every variable to the client. This is absolutely a good thing, but there are times when it’s necessary. Perfect example would be “public” API keys. Things that fuel a code snippet in your app. Stripe provide you with both a public and a secret key, for this very reason.

So how does one get variables to become available? It’s pretty simple, all you need to do is prefix your variable name with NEXT_PUBLIC_ and you will have access to it via process.env in your client-side component.

Where I was a bit thrown was I thought perhaps Next.js would magically strip the prefix, so when you want say NEXT_PUBLIC_SOME_VAR you’d access it as process.env.SOME_VAR.

Definitely not the case. Under the hood, Next.js knows to take any NEXT_PUBLIC_ variables and expose them to the client, retaining the name. That means NEXT_PUBLIC_SOME_VAR would be accessed as process.env.NEXT_PUBLIC_SOME_VAR.

I don’t necessarily love the longer variable names, but having the ability to keep everything in .env (or defined directly in my VPS provider‘s UI) is fantastic.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.