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:
- Define the environment variable in the
.env.localfile at the root of your project (create it if it doesn't exist):
dotenvNEXT_PUBLIC_API_URL=https://your-api-url.com
- In your code, you can use
process.env.NEXT_PUBLIC_API_URLto access this variable.
For example, in a component:
jsxfunction 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 回复