Blitz is now in beta! 🎉 1.0 expected this April
Back to Documentation Menu

Environment Variables

Topics

Jump to a Topic

Blitz comes with built-in support for environment variables, which allows you to do the following:

Loading Environment Variables

Blitz has built-in support for loading environment variables from .env.local into process.env.

An example .env.local:

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

This loads process.env.DB_HOST, process.env.DB_USER, and process.env.DB_PASS into the Node.js environment automatically allowing you to use them on the server.

Note: Blitz will automatically expand variables inside of your .env* files. This allows you to reference other secrets, like so:

# .env
HOSTNAME=localhost
PORT=8080
HOST=http://$HOSTNAME:$PORT

If you are trying to use a variable with a $ in the actual value, it needs to be escaped like so: \$.

For example:

# .env
A=abc
WRONG=pre$A # becomes "preabc"
CORRECT=pre\$A # becomes "pre$A"

Exposing Environment Variables to the Browser

By default all environment variables loaded through .env* files are only available in the Node.js environment, meaning they won't be exposed to the browser.

There are two ways you can expose a variable to the browser.

Option 1: NEXT_PUBLIC_ Prefix

Prefix the variable with NEXT_PUBLIC_. For example:

NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk

The value will be inlined into JavaScript sent to the browser because of the NEXT_PUBLIC_ prefix.

// pages/index.js
import setupAnalyticsService from "../lib/my-analytics-service"

// NEXT_PUBLIC_ANALYTICS_ID can be used here as it's prefixed by NEXT_PUBLIC_
setupAnalyticsService(process.env.NEXT_PUBLIC_ANALYTICS_ID)

function HomePage() {
  return <h1>Hello World</h1>
}

export default HomePage

Option 2: env in blitz.config.js

Any keys defined in env in your Blitz config will be inlined into JavaScript sent to the browser.

// blitz.config.js
module.exports = {
  // Env vars defined here will be PUBLIC and included in the client JS bundle
  env: {
    STRIPE_KEY: process.env.STRIPE_KEY,
    SENTRY_DSN: process.env.SENTRY_DSN,
  },
}

Different Values per Environment

In general only one .env.local file is needed. However, sometimes you might want to add some defaults for the development or production environment.

Blitz allows you to set defaults in .env (all environments), .env.development (development environment), .env.production (production environment), and .env.test (test environment). These files with defaults should be checked into git.

Appending .local will override the defaults. Examples: .env.local, .env.test.local. These files should not be checked into git.


Idea for improving this page? Edit it on Github.