Using environment variables in Next.js Frontend

By admin
Recently, in one of my Next.js projects

LinkSnatch
PERSON

, I needed to use API keys from jsonlink.io. Now, I didn’t want to hardcode the

API
ORG

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
ORG

=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
PRODUCT

_ like so.

NEXT_PUBLIC_JSONLINK_API_KEY=random_api_key

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

const

apiKey
ORG

= process . env . NEXT_PUBLIC_JSONLINK_API_KEY ; console . log (

apiKey
ORG

); // 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
ORG

and I wanted to use the same environment variables there as well.

To do that, you can go to the

Cloudflare Pages
ORG

dashboard, select your project, and then go to the “Environment Variables” section in the “Settings” tab and add the environment variables there like so.