Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I can see this.

I learned from a friend to use Zod to check for process.env. I refined it a bit and got:

```

const EnvSchema = z.object({

  NODE_ENV: z.enum(['development', 'production', 'staging']),

  DATABASE_URL: z.string(),

  POSTHOG_KEY: z.string(),
});

export type AlertDownEnv = z.infer<typeof EnvSchema>;

export function getEnvironments(env: Record<string, string>): AlertDownEnv { return EnvSchema.parse(env); }

```

Then you can:

```

const env = getEnvironments(process.env);

```

`env` will be fully typed!

Definitely, I need to do some improvements in my frontend logic!



I'm not familiar with Zod, but one thing that is quite important on the user end is to produce multiple (but, per policy, not infinite) error messages before giving up. That is, list all environment variables that need to be set, not just whichever one the code happens to be first.

This could be implemented with `??`, something like: `process.env.NODE_ENV ?? deferred_error(/temporary fallback/'', 'NODE_ENV not set')`, but is probably best done via a dedicated wrapper.


Yes use zod or equivalent.

I am quite surprised people here doesn't know how to validate data in runtime. The author completely mixing Typescript with runtime behavior.

a?.b?.c?.() or var ?? something have well documented use cases and it's not what the author is thinking.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: