In Next.js, the method to expose environment variables to the frontend environment is by using the specific environment variable prefix NEXT_PUBLIC_. By doing this, we can ensure that only environment variables starting with NEXT_PUBLIC_ are bundled into the frontend code. This is a security measure in Next.js to prevent accidental leakage of sensitive information in client-side code.
Steps:
-
Create environment variables: In your project root directory, you can create a
.env.localfile to store environment variables for local development. For example, if you want to expose an API URL to the frontend, you can do the following:plaintextNEXT_PUBLIC_API_URL=https://api.yoursite.comHere,
NEXT_PUBLIC_API_URLis the name of the environment variable, which starts withNEXT_PUBLIC_, meaning it will be exposed to the frontend code. -
Use environment variables in code: You can directly use these environment variables in any frontend code (such as React components), like this:
javascriptfunction Component() { return ( <div> <p>API URL: {process.env.NEXT_PUBLIC_API_URL}</p> </div> ); }Here,
process.env.NEXT_PUBLIC_API_URLwill be replaced with the actual environment variable value.
Example:
Suppose we are developing an application that displays weather information and needs to fetch data from a public API. We can set up and use the environment variables as follows:
.env.local
plaintextNEXT_PUBLIC_WEATHER_API_URL=https://api.weatherapi.com/v1/current.json
WeatherComponent.js
javascriptimport React from 'react'; function WeatherComponent() { const fetchData = async () => { const response = await fetch(`${process.env.NEXT_PUBLIC_WEATHER_API_URL}?key=your_api_key&query=London`); const data = await response.json(); console.log(data); }; return ( <div> <button onClick={fetchData}>Fetch Weather</button> </div> ); } export default WeatherComponent;
In this example, the frontend component WeatherComponent will be able to access the NEXT_PUBLIC_WEATHER_API_URL environment variable, which is included in the built frontend code and can be safely used for API requests.
This approach ensures that our frontend application can safely access the required configuration at runtime while protecting sensitive information that should not be exposed.