Using zod to validate env vars
Is there a pattern similar to the one recommend in the React world for accessing env vars only after they have been parsed & checked by zod?
Something like this: https://creatures.sh/blog/env-type-safety-and-validation/#validating-environment-variables
-------------------------------------
What have I tried?
I've read: https://docs.solidjs.com/configuration/environment-variables but here the type safety doesn't make it so the server won't start without those variables (which is what I'd prefer).
Moreover Zod also enables safety checks like checking that a string is a URL or is a specific set of possible strings that just defining the types doesn't.
10 Replies
:Worry_Think:
Does putting the envSchema.parse within entry-server file work?
the instructions in that post are for any JS app, so it works the same way for Solid
for TS, you can also extend the
global.d.ts
like such:
I have a module like the one described in the post but if I import it in a component then the hydration seems to get blocked or JS somehow can't run anymore and only the SSR page is rendered.
Probably because it accesses
process.env
from the top level or something. No errors, nothing.
And put it in a context of some sort? or how were you imagining accessing it from other modules?It's just for the server's modules
So in any server context, it should be within process.env
It's expected to run once only before everything's ever started
:Worry_Think:
Oh you mean just validate it there and then use
process.env
when you need it? If so, then I was wondering if I could instead of using process.env
(which is untyped) use env
(a custom variable) which is the result of z.parse
So that I both have env
validated and type safeAs soon as you parsed
You're expecting it to have required ENV variables
Then after that you can just
Your
process.env
is now typedIt doesn't seem as ergonomic as just having an
export const env = envSchema.parse(process.env)
but it will work, thanks 👍:Worry_CoffeeHMM:
Don't 😟 be 🙂
:Worry_CoffeeSmile: