Using Environment Variables
Because environment variables are not captured in source code, they're not as easily shared across machines. To set up environment variables for your repository you will need to take advantage of a number of Turborepo features.
Working with Next.js and other libraries that load environment variables
If your framework automatically loads environment variables from a particular file, such as .env, you must indicate to turbo the location of these files. This shows a baseline configuration for Next.js and Vite, who load their environment files themselves:
{
"$schema": "https://turbo.build/schema.json",
"globalDotEnv": [".env"],
"pipeline": {
"build": {
"dotEnv": [".env.production.local", ".env.local", ".env.production", ".env"]
},
"dev": {
"dotEnv": [".env.development.local", ".env.local", ".env.development", ".env"]
},
"test": {
"dotEnv": [".env.test.local", ".env.test", ".env"]
}
}
}Loading Your Own Variables
If you need to load a large number of environment variables into your environment just prior to execution, we recommend using dotenv-cli. It's the simplest way to bring your environment variables into your development tasks.
Turborepo does not load any .env files into the environment! Your task must handle loading of the .env files itself.
With locally-installed turbo
-
Place all of your variables into the root of your monorepo in a
.envfile. -
Install
dotenv-cliinto the root of your repository.
{
"devDependencies": {
"dotenv-cli": "latest"
}
}- Adjust your scripts to inject the environment variables into the
turbocommand.
{
"scripts": {
"dev": "dotenv -- turbo dev"
}
}- Add the
.envfile toturbo.json:
{
"globalDotEnv": [".env"],
"pipeline": {
"dev": {
"dependsOn": ["^build"]
}
}
}With globally-installed turbo
If you're using turbo globally, you'll also need to install dotenv-cli globally so you can put dotenv -- in front of the turbo command in your terminal:
dotenv -- turbo devAdvanced Configuration: Per-workspace Environment Variables
You may prefer to make your workspaces responsible for loading their own environment variables. This approach is more flexible and gives better results if you don't mind the extra configuration overhead in your package.json scripts.
To use this strategy:
-
Place your variables into
.envfile(s) in the root of the packages that they needed to be loaded in. -
Install
dotenv-cliin the workspace.
{
"scripts": {
"dev": "dotenv -e .env.development -- start-server",
"build": "dotenv -e .env -- bundle-app"
},
"devDependencies": {
"dotenv-cli": "latest"
}
}- Add the
.envfile(s) toturbo.json:
{
"globalDotEnv": [".env"],
"pipeline": {
"dev": {
"dotEnv": [".env.development"],
"dependsOn": ["^build"]
}
}
}