How to expose Next.js environment variables to the browser specific code

The Next.js React web application runs separate code on the server and in the browser. By default, the environment variables are only accessible in the server side script.

Warning: by exposing environment variables to the browser code you may reveal secrets. Make sure the exposed environment variables do not contain any secrets. If secrets are needed in the browser code, create an API page in the pages/api directory and fetch it from the browser code.

To use environment variables in the browser side script,

  • expose those in theĀ next.config.js file
module.exports = {
  ...
  
  env: {
    // declare here all your variables
    MY_ENVIRONMENT_VARIABLE: process.env.MY_ENVIRONMENT_VARIABLE,
  }
};
  • Restart the server for the change to take effect !!!
  • Read the environment variable value from process.env in the browser specific file.
<div className={styles.footer} >
  Version: '2023-06-22_01' &nbsp;{process.env.ENVIRONMENT}
</div>

Leave a comment

Your email address will not be published. Required fields are marked *