Комментарии:
amazing piece of code
ОтветитьYou failed Matt. These need to be validated at build time!!
ОтветитьI think it's cool for autocompletion but it's not a single source of truth, since you have to keep the .env file in sync with the types file, and actually that can cause issues in runtime (zod string trying to parse an undefined env variable). Correct me if I'm wrong
ОтветитьHey Matt... would it be wrong to use z.coerce.number() (or any other type) for example, to coerce the type? Like in your example, PORT: z.string() would become PORT: z.coerce.number()
ОтветитьAmazing!
Ответитьthat's nice, but it doesn't work with Vite ImportMetaEnv.
Ответитьcan i do without zod or yup?. just create an interface and pass.
ОтветитьI employed this and it's great, but then I found `znv` module, so using that instead to keep it even simple🤓
Ответитьonly legends use the npm package called 'envalid'
Ответитьsorry im new to this but what's the purpose with the zod libraries, can't I just write it with typescript?
Ответитьthis gives me ideas....
ОтветитьI personally just create a singleton class with the values in the form i want:
export class AppEnvironment {
public static readonly DATABASE_URL: string = process.env['DATABASE_URL'];
public static readonly CORS_WHITELIST: string[] = !process.env['CORS_WHITELIST'] ? [] : process.env['CORS_WHITELIST'];
public static readonly PORT: number = process.env['PORT'] ? parseInt(process.env['PORT']) : 3000;
public static readonly API_SECRET: string = (() => {
if (!process.env['API_SECRET']) throw new Error(`API_SECRET not set in process.env`);
return process.env['API_SECRET'];
})();
public static readonly AWS = {
S3_ARN: process.env['S3_ARN'],
SES_ARN: process.env['SES_ARN'],
};
}
I'm using `env.d.ts` file to "Declare global ... " code, its okay?
ОтветитьWith zod you can infer types so you could do:
CUSTOM_STUFF: z.infer.number()
And it would do the equivalent of String(process.env.CUSTOM_STUFF) , so that's not really an issue.
I still prefer exporting a dedicated object than messing with the node types but both options are acceptable to be honest
when i import .env file using doteng.config() in app.ts file
i can access process.env.someting in most of the files.
but few files for example helper.ts file or some file which are not directly calling from express router where i am not able to access process.env.something. env are not loading in these files
why ? how to fix this issue
This is just unecessary
ОтветитьI personally use cleanEnv from a package called envalid for my env variables. Keep up with your impressive videos.
ОтветитьWouldn't we want to use the implement keyword in this case?
ОтветитьNO, I will use the global type define :s
ОтветитьGod damn thanks a lot dude! I searched now the past few hours for it, but I wasn't able to figure it out by my own. And thank god I found your video. Subscribed your channel, so that I can hopefully see more such hepful content. :thumbsup:
ОтветитьGreat video. I would personally add the Readonly wrapper to make sure env vars are constant like this `interface ProcessEnv extends Readonly<z.infer<typeof envVarSchema>> {}`.
ОтветитьDo you have a way to make the key of process.env non-accessible if not defined? Ex: typescript will throw an error like if you define a constant object `as const` and you try to access the `key` that doesn't exist.
I like this method, but unfortunately, `process.env` still allows access to the key that is not yet defined with zod, which makes accessing `process.env` directly riskier.
So nice trick!
ОтветитьIncredible! And yes we love the short videos. Thanks
Ответитьwhat font did you use in the thumbnail ? Is that fira code ? it just looks so nice but fira code to me is not really that nice so i am curious though. Thanks
ОтветитьWe can do something like this:
import { z } from 'zod'
const envSchema = z.object({
STR: z.string(),
NUM: z.coerce.number(),
})
declare global {
namespace NodeJS {
interface ProcessEnv extends Record<keyof z.infer<typeof envSchema>, string | undefined> {}
}
}
const envVars = envSchema.parse(process.env)
It results in <string | undefined> for process.env.WHATEVER and full power of zod for the envVars
But I pass VITE_BASE_API=, it's not throwing error
I prefer validate with min()
const envSchema = z.object({
VITE_BASE_API: z.string().min(1),
});
Awesome stuff!
ОтветитьI love TypeScript and I wish I could be there to understand like all much about it definitely it is wizardry 😅😅😅😅
ОтветитьI prefer exporting the parsed variable so that I can also do z.coerce.number() or something similar which avoid repeatedly doing that
ОтветитьI use the envalid package for this
ОтветитьNope, use a module where you parse and export, then use that. no-process-env is an es-lint rule for a reason.
Ответитьyou could easily export transform env vars from such a file. For example for a positive integer you'd do: z.string().regex(/\d+/).transform(val => +val)
the refine method of zod could also be used for more complex values instead of regex. Now all I need is some presets for frameworks such as astro and Next.js :)
❤
ОтветитьI really don't get what zod offers over just plain TS?
ОтветитьYou could do z.coerce.number() or a transform, or refine
ОтветитьFaaa who is this guy? Click straight SUBSCRIBE. I think the next big thing is to give devs some pro tips like this.
ОтветитьReally appreciate the shorter format, yet clear explanations
ОтветитьWhy not use a proper configuration management library like convict or dotenvsafe ?
ОтветитьWouldn't it be better to just have a class model and use that as the source of truth throughout your app isolating it from using process.env ?
ОтветитьI was completely on board, until you mentioned that you can't use Numbers or Booleans. I appreciate that all environment variables are being passed around as Strings in Bash etc., but if you're constructing types on top of an existing layer like this, there should be a level of parse-ability/inference that allows for these additional types.
Being forced to keep all the types as Strings, at least to me, doesn't feel like that much of a benefit over using process.env itself
Actually you better parse the env at one place and export a decent schema because calling process.env involves calling C functions which is a negativ Performance impact when done too often
ОтветитьI like it if you're already using Zod. But bringing it Zod just for ENV validation is a little too expensive in my opinion. Don't you think?
ОтветитьGlobal mutation 😬
Fine, it's just types and a runtime parse. But I would rather import the parsed config.
Our team has been using the resulting parsed Zod object, but extending it further with coercions. Definitely interesting to override the global ProcessEnv interface.
ОтветитьThis looks really familiar 🤔
Ответить