Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Using environment variables in Next.js Frontend

Recently, in one of my Next.js projects LinkSnatch, I needed to use API keys from jsonlink.io. Now, I didn’t want to hardcode the API key in the codebase since it’s an open-source project. So, the best way to handle this is to use environment variables.

Environment variables in Next.js

To use environment variables in Next.js, you can create a .env.local file in the root of the project and add environment variables in the form of KEY=VALUE like so.

But since we want to access the environment variables in the frontend, we need to prefix the environment variable with NEXT_PUBLIC_ like so.

NEXT_PUBLIC_JSONLINK_API_KEY=random_api_key

Now, you can access this environment variable using process.env like so.

const apiKey = process.env.NEXT_PUBLIC_JSONLINK_API_KEY;

console.log(apiKey); // random_api_key

And that’s it! You can now use the environment variables in your Next.js frontend.

Using environment variables in Cloudflare Pages

Now, I have deployed this project on Cloudflare Pages and I wanted to use the same environment variables there as well.

To do that, you can go to the Cloudflare Pages dashboard, select your project, and then go to the “Environment Variables” section in the “Settings” tab and add the environment variables there like so.

Cloudflare Pages Environment Variables

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?