Documentation
Setting up .env files

🥷🏽 Setting up Environment Variables

In this chapter, you will learn how to set up environment variables for your SaaS project.

Create .env files

I conveniently added a .env.example file to the repo for you to use as a starting point.

Go ahead and rename the .env.example file into .env.{YOUR_STAGE_NAME} (we'll use this to load in variables for your local development environment). Then make another copy and simply call it .env (we'll use this for your production environment).

Passing environment variables to your infrastructure

In the Blitzship monorepo, we handle environment variables differently from traditional Next.js applications, because SST has a very particular way of loading environment variables.

💡

If you're interested in more details, go ahead and read through the SST documentation on Secrets (opens in a new tab)

Here's some guidelines:

  • Do not add .env files to individual packages. Always load in environment variables using the npx sst secret cli.
  • We have a secrets.ts file in the infra/ folder which servers as the central place for the rest of your infrastucture to get environment variables from.

Example

Here's an example of how secrets are loaded in the Blitzship monorepo

infra/secrets.ts
const secret = new sst.Secret("MySecret", "my-secret-placeholder-value");

Now, to set this secret for your local environment, run the following command:

terminal
npx sst secret set MySecret value

For production, you can set the secret using the SST CLI as well:

terminal
npx sst secret set MySecret value --stage production

Then, use the secret in your /infra folder like this:

infra/next.ts
import { mySecret, notSoSecret} from "./secrets"
 
new sst.aws.Nextjs("MyWeb", {
  link: [mySecret]
  environment: {
    NEXT_PUBLIC_NOT_SO_SECRET: notSoSecret.value
  }
});

Once linked, you can access the secret in your Next.js app like this:

packages/landing-page/app/page.tsx
// server-side
import { Resource } from "sst";
const mySecret = Resource.MySecret.valueRET
 
// client-side
const notSoSecret = process.env.NEXT_PUBLIC_NOT_SO_SECRET
💡

For Next.js projects specifically, variables will only be available in server-side code. To access on the client-side variables, prefix them with NEXT_PUBLIC_ when passing them in your infra code.

Load all environment variables at once

Once you have filled in your .env files, you can load all of them at once using the following command:

terminal
npx sst secret load .env.{YOUR_STAGE_NAME}

or for production:

terminal
npx sst secret load .env --stage production