What’s the difference between exposing environment variables in nextjs through the next.config.js vs with the NEXT_PUBLIC prefix?

NEXT_PUBLIC is a new feature added. Before, in order to set up environment variables, we had to set up both server and client, separately.

Environment variables that are placed in the .env file would be available only on the server-side, if you want to make your env variables available on the client-side you had to use next.config.js. We follow the separation of concerns principle here.

But setting env variables for the browser in the next.config was too much unnecessary typing. This was an example in next.config.js for the client side env:

module.exports = {
  env: {
    AUTH0_NAMESPACE: process.env.AUTH0_NAMESPACE,
    BASE_URL: process.env.BASE_URL
  }
}

With NEXT_PUBLIC, env variables will be available both client-side and server-side. env variables that are set with NEXT_PUBLIC will be exposed to the browser. So make sure that you do not expose sensitive data to the browser.

So in summary, adding the prefix NEXT_PUBLIC to your environment variables will have the same effect of exposing to the browser your environment variables as exposing them through next.config.js.

try this:

place this to .env or env.development file. NOT to next.config.js

 MY_VAR=10

then run this:

    console.log("MY var",process.env.MY_VAR);

both inside client component and getServerSideProps function.
if you check the browser console, you will get undefined, but on terminal, you will see

MY var 10

Leave a Comment