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.
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.
Like this article? Consider leaving aTip