Back to articles
Environment Variables in Next.js
One of the key features of Next.js is its support for environment variables. Environment variables are variables that are set outside your application, often by your operating system or hosting provider, and are used to configure your application at runtime. In this article, we'll look at how to use and set up environment variables with Next.js.
Setting Up Environment Variables in Next.js
The first step to using environment variables in Next.js is to create a file called .env.local in the root directory of your project. This file should contain your environment variables in the format VARIABLE_NAME=VALUE. For example, if you want to set a variable called API_KEY to the value 12345, you would add the following line to your .env.local file:
API_KEY=12345
Once you have set your environment variables in your .env.local file, you can access them in your Next.js application using the process.env object. For example, to access the API_KEY variable we set earlier, you can use the following code:
const apiKey = process.env.API_KEY;
Using Environment Variables in Next.js
Now that you know how to set up environment variables in Next.js, let's look at how to use them in your application.
Suppose you have an API endpoint that requires an API key to be passed as a query parameter. You can use the API_KEY variable we set earlier to pass the key to the API. Here's an example:
import fetch from 'isomorphic-unfetch';
const apiKey = process.env.API_KEY;
async function getData() {
const res = await fetch('https://api.example.com/data?apikey={apiKey}');
const data = await res.json();
return data;
}
In this example, we're using the fetch function from the isomorphic-unfetch package to make a request to an API endpoint. We're passing the API_KEY variable as a query parameter to the endpoint.