
Type-Safe Environment Variables in Convex
Have you ever had this happen to you? You (or your coding agent) are working away on some Convex code, everything is going great with the schemas, queries and mutations, then someone reaches for process.env.OPEN_AI_KEY instead of OPENAI_API_KEY. TypeScript says nothing, and you only find out at runtime.
That's because process.env is stringly typed. There's no way for the type system (or an agent) to know which variables exist or what shape their values should take.
Well NO MORE, as a new feature silently dropped in Convex 1.39.0 a couple of weeks ago that has largely flown under the radar but I think is really awesome. You can now declare your deployment's environment variables in code, with validators, and get a fully typed env object to use in your backend functions:
process.env.OPEN_AI_KEY; // before
env.OPENAI_API_KEY; // after
Let's take a look.
Declaring environment variables
So first make sure you are running Convex 1.39.0 or later. Then pop open your convex/convex.config.ts file and as part of your defineApp call you can now declare what environment variables your app expects:
// convex/convex.config.ts
import { defineApp } from "convex/server";
import { v } from "convex/values";
const app = defineApp({
env: {
OPENAI_API_KEY: v.string(),
LOG_LEVEL: v.optional(
v.union(v.literal("debug"), v.literal("info"), v.literal("error")),
),
},
});
export default app;
You can use validators from convex/values to declare what sort of shape you expect your vars to take, the same ones you already know from schemas and function arguments. One thing to note though: because env var values are always strings, only a subset of validators is supported here:
v.string(): any string valuev.literal("value"): an exact string valuev.union(v.literal("a"), v.literal("b")): one of several exact valuesv.optional(...): wraps any of the above to mark a variable as optional
So no v.number() I'm afraid, at least for now.
Now after you run npx convex dev, Convex is going to generate a typed env object that you can import inside your backend functions:
import { env } from "./_generated/server";
const openAiKey = env.OPENAI_API_KEY;
Super cool! Autocomplete works, typos are compile errors, and the value's type matches its validator.
Setting the variables
Now you obviously still need to set these environment variables on your Convex deployment, declaring them just tells Convex what to expect. You can set them in the dashboard:
Convex dashboard environment variable settings
Or via the CLI:
npx convex env set OPENAI_API_KEY
If you don't set a required variable, Convex is going to yell at you when you push:
Error: Unable to finish push to https://secret-buzzard-634.convex.cloud
Error fetching POST https://secret-buzzard-634.convex.cloud/api/deploy2/finish_push 400 Bad Request: MissingEnvironmentVariables: Hit an error while pushing:
Required environment variables are not set: OPENAI_API_KEY. Set them in the Convex dashboard or CLI before pushing.
And it's also going to yell at you if a value doesn't match its validator:
Error fetching POST https://secret-buzzard-634.convex.cloud/api/deploy2/finish_push 400 Bad Request: InvalidEnvironmentVariable: Hit an error while pushing:
Environment variable LOG_LEVEL does not match its declared validator: Value does not match validator.
Value: "foo"
Validator: v.union(v.literal("debug"), v.literal("info"), v.literal("error"))
Also really good.
By the way, notice that as you change an env var the dev process immediately picks it up and rebuilds, such a nice little quality of life thing:
09:49:27 Convex functions ready! (2.92s)
And this isn't just a push-time thing either. If you were to later change or remove a variable from the dashboard or CLI in a way that breaks the declaration, Convex isn't going to let that through, which protects us. Noice!
Why not Zod?
A natural question is why you can't use Zod or other validation libraries for the env var validation?
Environment variable validation happens in the Rust layer of Convex, where arbitrary JavaScript can't run, so right now we are limiting it to Convex validators.
Typed environment variables for components
Oh and components got a big upgrade here too. Component functions are isolated from the app's environment variables, so a component can declare the env vars it needs like this:
// my-component/convex.config.ts
import { defineComponent } from "convex/server";
import { v } from "convex/values";
const component = defineComponent("myComponent", {
env: {
API_KEY: v.string(),
MODE: v.union(v.literal("test"), v.literal("live")),
},
});
export default component;
And the parent app can wire those up when it uses the component, either by reference to one of its own variables or with a literal value:
// convex/convex.config.ts
import { defineApp } from "convex/server";
import { v } from "convex/values";
import myComponent from "@example/my-component/convex.config";
const app = defineApp({
env: {
OPENAI_API_KEY: v.string(),
MY_COMPONENT_API_KEY: v.string(),
},
});
app.use(myComponent, {
env: {
// Pass by reference: stays in sync with the app's variable,
// even when it changes between deploys
API_KEY: app.env.MY_COMPONENT_API_KEY,
// Or pass a literal value
MODE: "live",
},
});
export default app;
If a component declares required env vars then the app that installs it has to provide them, or the push fails. So no longer do you have to wonder whether you have set all the environment variables a component needs, only to have it crash on you at runtime!
Conclusion
So just to recap: you can now tell Convex that you expect some environment variables to be set for your deployment and that they take a particular type, and Convex enforces it in your editor, at push time, and on any later changes to those variables.
I love this because it feels very Convex-y doesn't it? Everything in Convex is just code, like your schema and your generated API, so it feels natural that the missing piece of state, the environment variables, gets the same treatment.
This is also obviously great for agents, for the same reason agents love Convex schemas and generated APIs: they get immediate context on what they can expect to be there at runtime and fast feedback when they get something wrong.
By the way, if you do still want to use process.env then go ahead, it ain't going anywhere, this new typed env stuff isn't a breaking change.
Until next time, cheerio!
Convex is the reactive backend platform that keeps up with you and your agents. Database, functions, workflow, sync, search, file storage, and more. All TypeScript, zero glue.