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

How to get Next.JS environment variables on client side?

1个答案

1

In Next.js, you can access environment variables on the client-side, but only those prefixed with NEXT_PUBLIC_. These variables are embedded into the application during the build process and can be directly accessed in client-side code.

For example, if you have an environment variable named NEXT_PUBLIC_API_URL and you want to access it in client-side code, you can do the following:

  1. Define the environment variable in the .env.local file at the root of your project (create it if it doesn't exist):
dotenv
NEXT_PUBLIC_API_URL=https://your-api-url.com
  1. In your code, you can use process.env.NEXT_PUBLIC_API_URL to access this variable.

For example, in a component:

jsx
function MyComponent() { const apiUrl = process.env.NEXT_PUBLIC_API_URL; // Use the value of apiUrl as the API URL // ... return ( <div> The API URL is: {apiUrl} </div> ); } export default MyComponent;

During the build process (using next build), Next.js inline all environment variables prefixed with NEXT_PUBLIC_ into the built code. Therefore, unlike on the server-side, client-side code should not contain sensitive information, as all such data is exposed to end-users.

2024年6月29日 12:07 回复

你的答案