In Next.js, if you want to pass NODE_ENV or other environment variables to the client, you need to use Next.js's environment variable configuration. By default, only environment variables prefixed with NEXT_PUBLIC_ are passed to the client for security reasons. This is because server-side environment variables may contain sensitive information and should not be exposed to the client.
For the NODE_ENV environment variable specifically, it is typically used to identify whether the application is running in development mode, production mode, or test mode. Next.js automatically sets the value of NODE_ENV based on different commands (e.g., next dev, next build + next start).
If you need to access this NODE_ENV variable on the client side, you can create a new environment variable, such as NEXT_PUBLIC_NODE_ENV, and define it in your Next.js project using process.env.NODE_ENV.
How to Set and Use
-
Set Environment Variables In the project root directory, create a
.env.localfile (for local development) and set:bashNEXT_PUBLIC_NODE_ENV=developmentOr set it during deployment according to the actual environment (typically in CI/CD pipelines):
bashNEXT_PUBLIC_NODE_ENV=production -
Use the Variable in Your Application In your Next.js page or component, access this environment variable using
process.env.NEXT_PUBLIC_NODE_ENV:jsxfunction MyComponent() { return ( <div> Current environment: {process.env.NEXT_PUBLIC_NODE_ENV} </div> ); } export default MyComponent;
Example
Suppose you are developing an application that needs to display different UI elements or handle logic based on the environment. Using the above method, you can easily switch and identify the environment.
This approach offers security and ease of management. You can control which environment variables are exposed to the client without risking sensitive information leakage. Additionally, using the NEXT_PUBLIC_ prefix clarifies the purpose of environment variables, facilitating team communication and understanding.