Overview
The quick answer is that Next.js (as of version 9.4) can use standard environment variables, defined via the command line, or in a .env file. Next.js will differentiate between environment variables that are inlined during the build process and environment variables available on the server.
Inlining just means injecting your variables contents into your code during the build process. This only happens once during build, which is different from regular env variables that are read from the environment during each request.
Next.js uses a simple convention to accomplish this. Variables that start with NEXT_PUBLIC_ will be inlined as part of your build output, all other variables will be pulled from the runtime during request execution on the server.
Example .env file
# Server Only
DB_CONNECTION_STRING
STRIPE_SECRET_KEY
# Inlined
NEXT_PUBLIC_GA_ID
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
Given the flexibility with Next.js to generate static pages or server rendered pages, this article will cover how to properly use environment variables to avoid accidentally leaking keys and secrets.
A Simple Convention
The following convention has worked well for me:
- If the variable is going to be used anywhere in html/javascript/css that is rendered to the browser, use
NEXT_PUBLIC_ - If the variable is only meant to be run on the server, like an API or within the
getStaticProps,getServerSideProps,getStaticPathsmethods, then use regular environment variables. - If you follow this convention, you should avoid accidental security leaks, and also bugs that can occur because Next.js pages are server-rendered and client-hydrated. This means regular environment variables are only available on the server-render and not on the client during hydrate, causing the variable to appear initially, then disappear on client hydrate.
The video below shows the effects of trying to use a non NEXT_PUBLIC env var in your markup code. Note that this does not happen in dev and only on your built code (next build).