乐闻世界logo
搜索文章和话题

How to expose an Environment Variable to the front end in NextJS ?

1个答案

1

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:

  1. Create environment variables: In your project root directory, you can create a .env.local file 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:

    plaintext
    NEXT_PUBLIC_API_URL=https://api.yoursite.com

    Here, NEXT_PUBLIC_API_URL is the name of the environment variable, which starts with NEXT_PUBLIC_, meaning it will be exposed to the frontend code.

  2. Use environment variables in code: You can directly use these environment variables in any frontend code (such as React components), like this:

    javascript
    function Component() { return ( <div> <p>API URL: {process.env.NEXT_PUBLIC_API_URL}</p> </div> ); }

    Here, process.env.NEXT_PUBLIC_API_URL will 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

plaintext
NEXT_PUBLIC_WEATHER_API_URL=https://api.weatherapi.com/v1/current.json

WeatherComponent.js

javascript
import 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.

2024年6月29日 12:07 回复

你的答案