How to deal with env variable being string | undefined when clientId is expecting only string?

I'm trying to think of a solution to this... any ideas? So far I'm just doing typeof, and if it is not string then error.
7 Replies
Samathingamajig
Are you using zod to parse your env file, like we use in create-t3-app? if you are, make sure that you import { env } instead of going off of process.env.*
nexxel
nexxel3y ago
people usually do as string but its better to validate using zod we have a very nice system in create-t3-app
amanuel
amanuelOP3y ago
No I don't like type assertion here ok, I'll try using zod Yeah I already created my own system, t3-stack scaffold wasn't ready yet @nexxel Any documentation on this zod?
nexxel
nexxel3y ago
a simpler way to validate would be like this
import { z } from "zod";

const envSchema = z.object({
NODE_ENV: z
.enum(["development", "production", "test"])
.optional()
.default("development"),
DATABASE_URL: z.string().url(),
});

export const env = envSchema.parse(process.env);
import { z } from "zod";

const envSchema = z.object({
NODE_ENV: z
.enum(["development", "production", "test"])
.optional()
.default("development"),
DATABASE_URL: z.string().url(),
});

export const env = envSchema.parse(process.env);
https://zod.dev now import env from here and everything will autocompleted and typesafe and it will throw an error if it doesn't match this schema
amanuel
amanuelOP3y ago
this is literally god mode they should call it "god" instead of "zod" Thanks for this suggestion
Scot
Scot3y ago
I mean what do you want to do if it's not defined? You could just throw yourself Or set it to a default
amanuel
amanuelOP3y ago
yeah, that's what I was doing
Want results from more Discord servers?
Add your server