Loading Environment Variables
- Place
.env*
files in the project root directory.
- Next.js automatically loads
.env*
files into process.env
.
Referencing Other Variables
- Next.js will automatically expand variables that use
$
to reference other variables e.g. $VARIABLE
inside of your .env*
files. This allows you to reference other secrets.
TWITTER_USER=nextjs
TWITTER_URL=https://x.com/$TWITTER_USER // <https://x.com/nextjs>
- If you need to use variable with a
$
in the actual value, it needs to be escaped e.g. \\$
.
Bundle environment variables for the browser
- Only environment variables with the
NEXT_PUBLIC_
prefix are inlined into the client-side bundle.
- During the build time, Next.js replaces every
process.env.[variable]
with a hard-coded value.
NEXT_PUBLIC_API_URL=https://api.example.com // Available in client components
SECRET_KEY=supersecret // Only available on the server (server components, server actions, route handlers)