Validate Environment Variables with `ArkType`
2025-03-11
Lately I’ve been trying ArkType
as a replacement of zod
for type validation in TypeScript. There’s nothing wrong with zod
, I think it’s a fantastic library that makes my life easier, but I listened to a podcast with the author of ArkType
and I was curious to see the difference. I’m not too bothered about the performance gains (I was nowhere near this being a problem with zod
) but I do like the simple API. Here’s an example with one of my most common use cases for the library:
The Problem
Handling environment variables in “vanilla” Node.js is annoying. The ideal DX for me is having auto-complete from the editor (so you can’t misspell a name) and type safety (knowing that a value will be there and is the right type, otherwise the code wouldn’t run).
The Solution
Luckily this is a great use case for runtime validation libraries. You can create a schema with all the variable names and types, and feed it process.env
to parse them and validate they are all there. If there’s something wrong, it throws an error and your code won’t run (which would happen anyways but with a less obvious error message).
I like creating a env.ts
file that’s essentially a smart .env.example
file.
import { type } from "arktype";
const envSchema = type({
SECRET_KEY: "string"
});
type Env = typeof envSchema.infer;
const env = envSchema(process.env);
if (env instanceof type.errors) throw env;
export default env as Env;
Now you can import env
anywhere in your code, reference any variable and get nice autocompletion and types. Also, you can Cmd+click
the env object and it takes you to the definition, which is always a plus in my books.
As you would expect, the Types GOAT Matt Pocock has a video explaining an alternative method that involves extending the type for ProcessEnv
that is globally available, but I find that approach hard to remember.
Final thoughts
I don’t think there’s a noticeable difference ArkType
and zod
, even the differences in the API are minimal and a matter of taste. The one thing I like more about ArkType
is the default error message style. I find it a lot easier to interpret than in zod
.