---
title: Environment Variables
description: How to handle environment variables in next-forge.
---

next-forge has a composable environment variable system that allows you to define and validate environment variables in a type-safe way for each package, then compose them together into a single environment variable file for the app.

## Overview

Type safety is provided by [@t3-oss/env-nextjs](https://env.t3.gg/), which provides runtime validation and autocompletion for all environment variables. Each package can define its own environment variables in a `keys.ts` file, which exports an `keys` object that contains all validated environment variables, separated into `server` and `client` variables.

These keys are then composed together into a single environment variable file for the app, located in an `env.ts` file in the root of the app.

## Environment variable files

As part of the initial setup script, each `.env.example` file is copied to a real environment variable file in each Next.js application and some packages. From here, you can fill in the variables yourself.

Here are the files you will need to fill in:

- `app/.env.local` - The app's environment variables.
- `web/.env.local` - The web app's environment variables.
- `api/.env.local` - The API app's environment variables.
- `packages/database/.env` - The database package's environment variables.
- `packages/cms/.env.local` - The CMS package's environment variables.

<Info>
  We're aiming to remove the need for the package environment variable files, so if you have any suggestions for how to do this, please let us know.
</Info>

## Validation rules

Each package's `keys.ts` file contains the validation rules for each environment variable. These are used to validate the environment variables in the `.env.local` files. You can inspect these files to see the validation rules for each variable.

<Tip>You should be as specific as possible with your validation. For example, if you know that a vendor secret starts with `sec_`, you should validate it as `z.string().min(1).startsWith('sec_')`. This will not only make your intent clearer to anyone reading your code, but will also help prevent errors at runtime.</Tip>

## Integration environment variables

Some environment variables will be added by integrations and other tooling. For example, environment variables prefixed with `SENTRY_` are automatically added to a Vercel project when you add the Sentry integration from the Vercel Marketplace. Additionally, `VERCEL_PROJECT_PRODUCTION_URL` is a very handy environment variable that refers to the "production" URL to which this project is deployed on Vercel.

## Adding an environment variable

To add a new environment variable, you need to do two things:

1. Add the variable to each of the `.env.local` files across the project
2. Add the variable to the `server` or `client` object in the relevant package's `keys.ts` file.
