You're typing process.env wrong

Поділитися
Вставка
  • Опубліковано 17 кві 2023
  • Typing your environment variables with Zod is SUPER ergonomic and, if I say so myself, rather beautiful.
    TS Playground: tsplay.dev/WYe7EW
    Become a TypeScript Wizard with my free beginners TypeScript Course:
    www.totaltypescript.com/tutor...
    Follow Matt on Twitter
    / mattpocockuk
    Join the Discord:
    mattpocock.com/discord

КОМЕНТАРІ • 205

  • @noheadphones123
    @noheadphones123 Рік тому +57

    Honestly these short videos are replacing dumb memes and stuff for my daily quick watch or youtube shorts feed. So I really appreciate your work in these tid bits, not all will be useful to me but the seed is planted for future edge cases.

  • @boian-inavov
    @boian-inavov Рік тому +3

    These shorts are quick, condensed and really useful. I love them! 👌

  • @NedCollyer
    @NedCollyer Рік тому +115

    I was using the NodeJS namespace with the z.infer trick, however I found it better to do `export env = envVariables.parse(process.env)`, Then in my envVariables schema, I use transform or coerce
    - so my env becomes typed (eg, numbers, booleans etc from a .env file)

    • @seannewell397
      @seannewell397 Рік тому +4

      I like this - it gives control and one place where settings change and are managed, still in a global/static way.

    • @chungweileong
      @chungweileong Рік тому +3

      Well, there's actually a limitation to this approach, if you try to intialize something globally (for instance, database connection) when the server starts-up, you will notice that the `env` will always/sometimes return undefined, as it's not ready.

    • @mudscuffer
      @mudscuffer Рік тому +2

      @@chungweileong Sounds like you have some other issue. Import loop? Or async parsing perhaps?

    • @GuyGooL4
      @GuyGooL4 Рік тому +6

      @@chungweileong I think mutating the env or lazy loading it is a problematic practice, you could store lazy loaded or deferred stuff in another globally available variable.
      The approach of exporting env globally works fantastically when you rely on env variables that should be present on the program's initial start, whether it be a node server or even a frontend framework

    • @Sammi84
      @Sammi84 Рік тому +3

      @@chungweileong don't mutate your env from inside your application. Env is for passing data to your application.

  • @carlosconejo3880
    @carlosconejo3880 Рік тому

    Thanks Matt! keep em coming, learning a ton from these vids!

  • @farahrayis5928
    @farahrayis5928 Рік тому

    Incredible! And yes we love the short videos. Thanks

  • @zheil9152
    @zheil9152 Рік тому +159

    I would rather import the parsed env from a separate file than mess with the global interface that expects strings. It’s not really much effort considering the intellisense just auto imports from the correct place anyway.

    • @fallenpentagon1579
      @fallenpentagon1579 Рік тому +8

      and you can't forget to actually validate the process env. For example if you're code has multiple entry points you need to make sure that everyone of them actually calls envVariables.parse

    • @davidadamson1588
      @davidadamson1588 Рік тому +8

      Matts approach seems to be quite elegant and is impressive. But what @zheil says, is the way! The usage of zod to simplify validation is really convenient though 🎉

    • @Gigusx
      @Gigusx Рік тому +4

      @@davidadamson1588 To be honest, to me this jumps out as a great opportunity for Typescript to make some improvements to interaction of env vars with the rest of your code.

    • @davidadamson1588
      @davidadamson1588 Рік тому +3

      @@Gigusx I am not sure if I am a little old school…
      But I prefer to have such things as configuration in its own place, like inside a class. This helps to comply with the SOLID principle which again ensures the correct usage of eg a strategy pattern. Since when done properly, it will allow me to simply exchange the source of configuration by swapping out the configuration strategy. Strategies could be: loading configuration from a file or env vars or a combimation of both or what ever suits your needs.
      Hardcoding against process.env is not a thing you should do (in my opinion). Code against abstractions not concretions.
      People might argue that this is a „java thing“, but it has the same advantages when used with typescript, especially when working on large scale projects.

    • @havokgames8297
      @havokgames8297 Рік тому +5

      @@davidadamson1588 It has the same downsides too. You added complexity that you carry for the life of the project which you may never take advantage of. Put them in a class sure, but strategy pattern? abstractions? If you love acronyms then don't forget KISS.

  • @nsuid7499
    @nsuid7499 Рік тому

    Keep putting out more of these video. you're making great content

  • @xypnox
    @xypnox Рік тому +1

    Really appreciate the shorter format, yet clear explanations

  • @SachinSomia
    @SachinSomia Рік тому +2

    I really like these short videos!

  • @VerhoevenSimon
    @VerhoevenSimon Рік тому

    I love these interesting short videos.

  • @pulserudeus7968
    @pulserudeus7968 Місяць тому

    awesome find! thanks

  • @danieltran7637
    @danieltran7637 Рік тому

    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:

  • @alexmalinin2387
    @alexmalinin2387 Рік тому

    Awesome stuff!

  • @scumbag_kiko
    @scumbag_kiko Рік тому

    I absolutely love this

  • @jakubmalinowski1474
    @jakubmalinowski1474 Рік тому +1

    oh cmon man, id love to use that on my engineer degree project if only this video was created 2 months ago. I was so struggling with process env on typescript.
    This was so helpful either way, thank you

  • @leopardgaming0144
    @leopardgaming0144 5 днів тому

    very very thanks for this video.really helpful

  • @saifullahrahman
    @saifullahrahman Рік тому

    wow! I recently gave up trying to type these env variables. Thanks a lot!!

  • @unknownChungus
    @unknownChungus Рік тому +2

    In our team we use JOI. Works perfectly fine. We create functions and group similar env in its return obj and import that function and use it at the place we need.

  • @MikeBifulco
    @MikeBifulco Рік тому +26

    THIS IS SO HELPFUL - Matt, I can't tell you how much I've learned from your channel in a short amount of time. Thank you - keep up the great work!

  • @BBStub3
    @BBStub3 8 місяців тому

    amazing piece of code

  • @souvlaki42
    @souvlaki42 Рік тому

    I personally use cleanEnv from a package called envalid for my env variables. Keep up with your impressive videos.

  • @novailoveyou
    @novailoveyou Рік тому

    It's quite nice. I really like it

  • @some_user_880
    @some_user_880 Рік тому

    So nice trick!

  • @leo11877
    @leo11877 Рік тому

    This is gold!

  • @joe_xyz
    @joe_xyz Рік тому +18

    Zod is such a great and incredibly useful library, I feel like I'm not exaggerating when I say it's currently the best package on npm by far.

    • @parlor3115
      @parlor3115 Рік тому +1

      One thing to note about zod though, is that it sucks with cross field validation

    • @joshuakb2
      @joshuakb2 Рік тому

      ​@@parlor3115 wouldn't the refine method serve that need?

    • @uziboozy4540
      @uziboozy4540 Рік тому

      @deepkit/type is far superior to that garbage

  • @thisweekinreact
    @thisweekinreact Рік тому

    nice, didn't think about it 👌

  • @blueghost512
    @blueghost512 Рік тому

    I was using this approach with NodeJS (no TS), but I started using TS with this approach and really got into problems with other types like numbers (PORT for example).
    So now I'm using an interface that is applied to a getter function, in the getter I can covert the var into real number, and also I added a default value functionality.
    So now I have a centralized function working as a getter for the env vars, that can cast types and use default values if you var is not set.

  • @torickjdavis
    @torickjdavis Рік тому

    Our team has been using the resulting parsed Zod object, but extending it further with coercions. Definitely interesting to override the global ProcessEnv interface.

  • @alpakarosa3678
    @alpakarosa3678 Рік тому +2

    I was always trying to understand why my process.env.VARIABLE could be string or undefined, this helped me a lot

  • @DEV_XO
    @DEV_XO 11 місяців тому

    Amazing!

  • @Mitsunee_
    @Mitsunee_ Рік тому +1

    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 :)

  • @DrWarpMan
    @DrWarpMan Рік тому +5

    This is really interesting, I think I will try this, I have been doing the second version which is exporting Zod parsed process.env.
    But what you did here is made it type safe and globally available without the need to export. Which is cool, but the downside is as you said they are all strings by default, and I prefer, when working with booleans or numbers, to really have them as numbers.

    • @Erandros
      @Erandros Рік тому

      (UPDATE: WHOOPS, this is incorrect)
      Many js libraries that provide a build process parse things like `process.env.MY_ENV_VAR`, and replace them with the actual env var found at build time.
      If you export the parsed object that won't happen while @mattpocockuk 's solution will work with that.
      Without such feature, I'd agree with your solution and the lack of ability to transform data.

    • @davidadamson1588
      @davidadamson1588 Рік тому +2

      @@Erandros no. Matts solution will not work as well when using such build tools! This is due to the fact, that process.env cannot be validated by zod (since env vars are getting replaced individually). Typing process.env globally without having the validation will result in pure nonsense.

    • @Erandros
      @Erandros Рік тому +1

      @@davidadamson1588 sorry

    • @davidadamson1588
      @davidadamson1588 Рік тому +1

      @@Erandros no reason to be sorry. I hope my comment did not offend you 😨

    • @Erandros
      @Erandros Рік тому +1

      @@davidadamson1588 not at all, I just felt ashamed that I gave inaccurate information, but that's on me, dont worry

  • @burnhard2
    @burnhard2 Рік тому +5

    This is great! What do you think of using `z.input` instead? Then you could even do transforms, for example to convert CUSTOM _STUFF to a number, while still retaining autocomplete and correct types on process.env.
    z.infer is an alias of z.output, but sometimes you want the input types instead, such as on process.env.

  • @gularz1982
    @gularz1982 Рік тому

    So cool!

  • @balduin_b4334
    @balduin_b4334 Рік тому

    the t3 stack also does this, but with an own "env" variable that is being exported. Also the declare 2 schemas: client schema and server schema.
    i find it pretty useful (yes I know the client schema is a little bit more expense, variable has to start with "NEXT_PUBLIC_..." and so on )

  • @antontimeboy6094
    @antontimeboy6094 Рік тому

    You can also transform the env variables inside the zod schema, from strings to eg. Date.
    You won't be able to do the `interface extends ...` trick, because that still only accepts strings.. But you can parse the envs and export them, just like you did for a second there.

  • @gdnight
    @gdnight Рік тому

    Have you heard of the znv package ? It does all of this and then some. Uses zod, parses into whatever type you're expecting your variable to be, and lets you provide defaults for each environment that NODE_ENV might be set to.

  • @jubayerabdullahjoy2582
    @jubayerabdullahjoy2582 Рік тому

    UA-cam should look into adding a love react button, this video requires so much of it!
    Thanks Matt, this is awesome!

  • @emkisn
    @emkisn Рік тому +1

    I love these small videos, please keep sharing these superb ideas with us!
    I already did something really similar to that and the only problem I had is if you add to this env object the isDev property based on the "NODE_ENV === development" when you build to production your bundle might not strip out the code you have that is only related to development

    • @emkisn
      @emkisn Рік тому

      So then to make this work I just used the process.env.NODE_ENV directly for these cases, and other places I access the env properties from this custom object.

    • @dealloc
      @dealloc Рік тому +1

      @@emkisn Yeah I wouldn't use this for env variables I don't control. NODE_ENV being an example of this, or even PATH in POSIX because it shouldn't matter that they don't exist in those cases, there should be a reasonable fallback for those cases.

    • @emkisn
      @emkisn Рік тому

      @@dealloc Makes sense, the only thing that borders me is that then we will have two different ways to access env variables, so it's not really consistent. Maybe an ESLint rule to only allow certain kinds of it usages like NODE_ENV could help with that.

  • @Learnbynet
    @Learnbynet Рік тому

    nice one

  • @wlockuz4467
    @wlockuz4467 Рік тому

    Mind blown!

  • @najlepszyinformatyk1661
    @najlepszyinformatyk1661 Рік тому

    nice approach actually i did follow an export approach

  • @DjLeonSKennedy
    @DjLeonSKennedy Рік тому

    Nice!!

  • @CanRau
    @CanRau Рік тому

    You could do z.coerce.number() or a transform, or refine

  • @skylerdjy
    @skylerdjy Рік тому

    The parse would also fail and prevent the app from starting; instead of running into a runtime error or bug down the line, if the environment variables are not defined, which is also another benefit!

  • @somebody656
    @somebody656 Рік тому +1

    I prefer exporting the parsed variable so that I can also do z.coerce.number() or something similar which avoid repeatedly doing that

  • @MelroyvandenBerg
    @MelroyvandenBerg 3 місяці тому

    I migrating to Fastfiy, and I'm also considering Zod now. It seems very superior to alternatives also for documenting API end points / schemas.

    • @MelroyvandenBerg
      @MelroyvandenBerg 3 місяці тому

      ps. Hopefully this Zod + process env also works together with dot env eg. @fastofy/dot-ev?

  • @jeffnikelson5824
    @jeffnikelson5824 11 місяців тому

    sorry im new to this but what's the purpose with the zod libraries, can't I just write it with typescript?

  • @wfl-junior
    @wfl-junior Рік тому +1

    I never thought of this approach and I really like it, this video timing was pretty good actually, I had an issue today in production because of an environment variable that I forgot to add in production, this would've helped me find the issue faster.
    I'm going to do this from now on, great stuff!

  • @MarcoBiedermann
    @MarcoBiedermann Рік тому

    I've used `env-var` in the past to validate, parse and type my environment variables

  • @abiodun6897
    @abiodun6897 Рік тому

    so many things to learn lol

  • @codestalk9183
    @codestalk9183 Рік тому

    this gives me ideas....

  • @brangtoggez6363
    @brangtoggez6363 Рік тому

    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

  • @RobertKonigsberg
    @RobertKonigsberg 5 місяців тому

    I'm looking at creating environment variables that can be parsed by JSON. Seems there's a standard way to do that, and I wish the example you provided made it easy to do that, as well.

  • @mattmarkus4868
    @mattmarkus4868 Рік тому

    1:51 what is "types node"? Do you mean @node/types or something? I want to use this in our proj for urls and other global settings. Very cool. Thanks.

  • @Luxcium
    @Luxcium Рік тому

    I love TypeScript and I wish I could be there to understand like all much about it definitely it is wizardry 😅😅😅😅

  • @codinginflow
    @codinginflow Рік тому

    I use the envalid package for this

  • @kalelsoffspring
    @kalelsoffspring Рік тому

    I've seen a lot of developers who are fine duplicating static information like that, this is so much nicer :)

  • @dieguitto08
    @dieguitto08 6 місяців тому

    Is there a way to do the same with ImportMeta?

  • @huynhthien4316
    @huynhthien4316 Рік тому

    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.

  • @juliusmarminge
    @juliusmarminge Рік тому +2

    This is great although it lacks the support of transforms, for example of boolean coercions, using default values etc.
    Due to the lack of transforms, a more correct way to infer the schema here is to use the _input type of the validator so that no transforms are affectign the types of the process.env. But this is a nevertheless a great way to get a simple validation that you're not missing any envs on build!

  • @laluneodyssee4404
    @laluneodyssee4404 Рік тому +1

    I like envalid for this solution

  • @Vendavalez
    @Vendavalez Рік тому

    This seems helpful if you’re using envars for anything other than the main of your program, but that has turned out to be a bad idea every time I have done it so I just don’t do that anymore.

  • @xtinctspecies
    @xtinctspecies Рік тому

    Why not use a proper configuration management library like convict or dotenvsafe ?

  • @ravenMK_
    @ravenMK_ Рік тому

    Helpful video. Wondering how I could use that with a .env file? Would really appreciate support of this. Thanks

    • @mattpocockuk
      @mattpocockuk  Рік тому

      This is designed to work with a .env file!

  • @wayneswildworld
    @wayneswildworld Рік тому

    Wouldn't we want to use the implement keyword in this case?

  • @mahadevovnl
    @mahadevovnl Рік тому

    Can't you use Zod to enforce all env variables to be strings and never anything else?

  • @Ked_gaming
    @Ked_gaming Рік тому

    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

  • @milon27
    @milon27 Рік тому

    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

    • @mattpocockuk
      @mattpocockuk  Рік тому

      Call dotenv.config() before you do your imports.

  • @roach_iam
    @roach_iam Рік тому +4

    Is there any reason why this is better than "only adding it to the ProcessEnv"? Why use zod at all for this?

    • @nicolaichristensen6531
      @nicolaichristensen6531 Рік тому +9

      If we forget an environment variable zod will just throw an error for us instantly and we won't have to debug and find out what's missing.

    • @thuytv3814
      @thuytv3814 Рік тому +1

      I have that same question, what is the benefit of zod here...

    • @idonoD
      @idonoD Рік тому

      What Nicolai said. Free Validation and typing is the key here

  • @PatrikTrefil
    @PatrikTrefil Рік тому

    Great video. I would personally add the Readonly wrapper to make sure env vars are constant like this `interface ProcessEnv extends Readonly {}`.

  • @KnThSelf2ThSelfBTrue
    @KnThSelf2ThSelfBTrue Рік тому

    I don't think you can ever get rid of process.env, and this is the best way to handle it, but for env vars in general, I like to have a solution with one more trick up its sleeve:
    Wrapping the var in a getter that is refetched/decrypted from a config/secret store at the time of access (with reasonable amounts of in-memory caching where necessary) and then garbage collected. That way, if the node is compromised, the secrets are not on disk, and only a temporary access token can be stolen.

  • @tanishqmanuja
    @tanishqmanuja Рік тому

    Saw this first in create T3 app, using it since then.

    • @mattpocockuk
      @mattpocockuk  Рік тому +1

      Do they do the declare global thing in T3? I thought they used the export const envVariables setup.

    • @tanishqmanuja
      @tanishqmanuja Рік тому

      @@mattpocockuk Correct, it uses export const env setup with a variation that allows to throw error if env vars are accessed client side. But extending global namespace interfaces is certainly a neat idea.

  • @noamisaac
    @noamisaac Рік тому +2

    The problem with this is that mutation don't work. If you export the parsed object and use it in place of environment variables, however...

    • @mattpocockuk
      @mattpocockuk  Рік тому +1

      Could you rephrase your question? It works great.

    • @artistry7919
      @artistry7919 Рік тому +1

      Wym? You want to mutate the env variables?

    • @noamisaac
      @noamisaac Рік тому

      @mattpocockuk look at libraries like envalid and envsafe. Instead of parsing the result and than doing nothing with the actual result object, we can parse the environment and than export it (I like to than add a path to it in the tsconfig, I.e. @/env) and use the resulting object instead of process.env. That way, any mutation you make to the environment variable (for example, using JSON.parse to turn a stringified object into a string proper) can be used

  • @snatvb
    @snatvb Рік тому

    nice :)

  • @sankasanjeeva1182
    @sankasanjeeva1182 11 місяців тому

    can i do without zod or yup?. just create an interface and pass.

  • @austincodes
    @austincodes Рік тому

    This looks really familiar 🤔

  • @sergeyzwezdin
    @sergeyzwezdin Місяць тому

    Thank you for the video, but I think there is an issue.
    Imagine you have PORT: z.number() in your schema.
    While you extend ProcessEnv, typescript considers it as actual number, but in your process.env.PORT is still string, which can cause the bugs typescript unable to catch.

  • @SergiySev
    @SergiySev Рік тому

    What is `interface ProcessEnv` and how is it related to `process.env`?

    • @SergiySev
      @SergiySev Рік тому

      @Clemens Horn thx, i was wandering from where `ProcessEnv` came, so apparently it is a part of NodeJS typings in typescript. good to know

  • @xtraszone
    @xtraszone Рік тому

    I do it without using any other plugin using only typescript

  • @crizo23
    @crizo23 Рік тому

    Cool! I might be confused though - how does this give us "type safety"? Like you said, process.env.X is a string by default. It seems to me that the only benefit here is autocomplete. Am I wrong?

    • @mattpocockuk
      @mattpocockuk  Рік тому +1

      process.env.X is string | undefined by default!

    • @TechBuddy_
      @TechBuddy_ Рік тому

      It gives you runtime safety by ensuring that the env variable you are accessing actually exists

    • @crizo23
      @crizo23 Рік тому

      @@mattpocockuk ahh, true. Thanks!

  • @shahreazneeloy2119
    @shahreazneeloy2119 Рік тому

  • @GrSurnov
    @GrSurnov Рік тому

    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 {}
    }
    }
    const envVars = envSchema.parse(process.env)
    It results in for process.env.WHATEVER and full power of zod for the envVars

  • @r0n472
    @r0n472 Рік тому

    Why do this instead of exporting and using the envVariables object to retrieve the environment variables?

    • @mattpocockuk
      @mattpocockuk  Рік тому

      I address this in the video itself. I find it just a bit more truthful. process.env.WHATEVER _is_ available, so why not make it type safe?

    • @scezar8880
      @scezar8880 Рік тому

      @@mattpocockuk only issue is that if you add something like "DEBUG_LEVEL: z.number()" on the object, TS will assume that process.env.DEBUG_LEVEL is a number, which would be wrong

    • @mattpocockuk
      @mattpocockuk  Рік тому

      @@scezar8880 That's not correct. It'll conflict with the built-in ProcessEnv type, so it'll give you the proper error.

  • @trapperxzw
    @trapperxzw Рік тому

    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 ?

  • @chungweileong
    @chungweileong Рік тому

    I actually like this approach, but the only problem I have with this is that it doesn't stop people from using a variable without define in the zod schema. Instead, I personally prefer to have a `env('....')` function, to use & validate variable on-demand, and allow you to do some cool stuff like throwing error when someone try to use non-NEXT_PUBLIC_ variable in NextJS frontend.

    • @dealloc
      @dealloc Рік тому

      The problem with that is Next is not able to transform your `env(...)` calls during build time, which makes it unusable in client-side code.
      The same problem happens when during process.env[someArbitraryKey]. Next cannot inline those environment variables. Same if you were to destructure, or assign process.env to a variable.

  • @ikarosouza
    @ikarosouza Рік тому

    I find it better to import the parsed object

  • @marcoscarlomagno3065
    @marcoscarlomagno3065 11 місяців тому

    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

    • @mattpocockuk
      @mattpocockuk  11 місяців тому

      The point of this is that zod ENSURES that your .env file is correct.

  • @codefinity
    @codefinity 11 місяців тому

    I employed this and it's great, but then I found `znv` module, so using that instead to keep it even simple🤓

  • @JakobBjerrePetersen
    @JakobBjerrePetersen Рік тому

    Why should I bother doing this in Zod instead of just creating a regular interface? (Honest question)

    • @mattpocockuk
      @mattpocockuk  Рік тому

      Because you'll be sure that at runtime, the correct env variables are being passed in

    • @JakobBjerrePetersen
      @JakobBjerrePetersen Рік тому

      @@mattpocockuk Ah yes. That makes sense. Thanks for your answer!

  • @anhvuuc8693
    @anhvuuc8693 Рік тому

    NO, I will use the global type define :s

  • @LewisCowles
    @LewisCowles Рік тому

    Nope, use a module where you parse and export, then use that. no-process-env is an es-lint rule for a reason.

  • @mathiasmaerker613
    @mathiasmaerker613 Рік тому

    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

  • @jakub7048
    @jakub7048 11 місяців тому

    only legends use the npm package called 'envalid'

  • @Poxen
    @Poxen Рік тому

    zod not needed for this? can just do the same thing with the declare global thing

    • @mattpocockuk
      @mattpocockuk  Рік тому

      Yep, true! Just wanted to show the awesome z.infer thing

    • @Erandros
      @Erandros Рік тому +2

      not needed, assuming you're gonna typecheck process.env manually, otherwise you're assigning a type to it that isn't accurate

    • @Poxen
      @Poxen Рік тому

      @@mattpocockuk oh yeah! that way u don’t need to add types manually, honestly could save a lot of confusion!

  • @amir-ziaei
    @amir-ziaei Рік тому

    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?

    • @mattpocockuk
      @mattpocockuk  Рік тому

      Yes, but you're probably going to be using it anyway!

  • @gokudomatic
    @gokudomatic 11 місяців тому

    that's nice, but it doesn't work with Vite ImportMetaEnv.

  • @elliotheath5366
    @elliotheath5366 Рік тому

    Monorepo?

  • @chhiethearith9525
    @chhiethearith9525 Рік тому

    we can do this if you not using zod ==> declare global {
    namespace NodeJS {
    interface ProcessEnv {
    DB_HOST: string;
    DB_PORT: string;
    }
    }
    }

    • @mattpocockuk
      @mattpocockuk  Рік тому

      Yes, though this won't give you any runtime validation.

  • @karmasakshi
    @karmasakshi Рік тому

    Nice. Or one can use envalid; works great and throws relevant errors.