Our apps and packages are in a Turborepo monorepo that we deploy on Vercel. Most of our packages have a constants file that use some environment variables in order to do things like make requests to the right endpoints if in dev versus prod. We wrote a little script that takes the constants exported from that file and checks to make sure they all have values on them. Is there a way to run that script during a prebuild or postbuild of our applications that use them and if an environment variable is not set, have it cause the app build to fail? I've tried it on prebuild but it is failing even though the environment variables are set. I'm assuming it's because Vercel injects the environment variables after building or something along those lines.
You're right about the timing of environment variables in Vercel deployments. There are a few important things to understand about how environment variables work in Turborepo monorepos on Vercel:
.env
Files: Turborepo itself doesn't load .env
files into your task's runtime. This is left to your framework or tools like dotenv
1. However, Turborepo needs to know about these variables for proper hashing.turbo.json
configuration 1.Here are a few approaches to solve your problem:
--env-mode=loose
FlagIf you're having issues with environment variables not being found during builds, you can use Loose Mode:
turbo run build --env-mode=loose
This makes it easier to get started, but be aware that it doesn't filter environment variables according to your globalEnv
and env
keys 1.
turbo.json
Make sure your turbo.json
properly declares all environment variables:
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"env": [
"API_URL",
"OTHER_ENV_VAR"
// List all env vars used in builds
]
}
},
"globalEnv": [
// Env vars that affect all tasks
"NODE_ENV"
]
}
Instead of using prebuild, consider:
Here's an example of a custom build script in your package.json:
{
"scripts": {
"build": "node validate-env.js && next build",
"validate-env": "node validate-env.js"
}
}
eslint-config-turbo
Turborepo provides an ESLint config that helps you find environment variables used in your code that aren't listed in your turbo.json
1. This can help ensure all your environment variables are properly accounted for.
.env
files in packages rather than at the root of the repository 1--summarize
flag to identify any missing environment variables in your configuration 1By implementing these changes, you should be able to properly validate your environment variables during the build process.