NEXT_PUBLIC
introduces a new feature to simplify the setup of environment variables. Previously, configuring environment variables required separate setups for server and client.
In the past, environment variables stored in the .env file were only accessible on the server-side. To make these variables available on the client-side, developers had to use next.config.js
, following the separation of concerns principle.
However, configuring env variables in the next.config
file involved unnecessary typing. Here is an example from next.config.js
for setting up client-side env variables:
module.exports = {
env: {
AUTH0_NAMESPACE: process.env.AUTH0_NAMESPACE,
BASE_URL: process.env.BASE_URL
}
}
With NEXT_PUBLIC
, environment variables can now be accessed on both the client-side and server-side. Variables configured with NEXT_PUBLIC
will be exposed to the browser, so caution must be taken not to expose sensitive information.
In essence, adding the prefix NEXT_PUBLIC
to your environment variables achieves the same outcome of exposing them to the browser as using next.config.js
.
To test this feature, try placing the following in either the .env or env.development file, NOT in next.config.js
:
MY_VAR=10
Then, run the following code:
console.log("MY var",process.env.MY_VAR);
Execute this code within a client component and the getServerSideProps
function. When you check the browser console, you will see undefined
. However, in the terminal, you will see:
MY var 10