0

According to Next.js docs on environment variables:

By default environment variables are only available in the Node.js environment, meaning they won't be exposed to the browser.

In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_. For example:

NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk

Isn't the whole point to avoid environment variables being exposed? Is it safe to use NEXT_PUBLIC_... with secrets one doesn't want page visitors to have access to e.g. API Keys?

The docs go on to say that the variables are loaded at build time but does not explain whether or not someone can access them from the browser after the project has been deployed.

  • Do not use `NEXT_PUBLIC_` prefix for sensitive secrets that should not be visible on the browser - using it will expose them. Using the prefix for variables that would otherwise be needed on the client-side anyway, like a GA ID, is perfectly fine though. – juliomalves Jul 20 '22 at 18:18

1 Answers1

2

The env variable values starting with NEXT_PUBLIC_ are inlined into the code. The variable name will be replaced by the actual value and this value is exposed to the user on inspection of chrome dev tools.

The point of environment variables, according to me is to have different values based on the environment. Security is something you are getting with it, if implemented correctly.

In next.js's case, you have the option to use server side environment variables which do no start with NEXT_PUBLIC_. If you really want to secure your keys, keep them only in code that runs on the server side like getServerSideProps, middleware etc.

Example : You want to make an API call, just call the next.js API (another server side only feature) and do the actual API call from there. That way your API_KEY is protected.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39