You're typing process.env wrong

You're typing process.env wrong

Matt Pocock

1 год назад

54,993 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@BBStub3
@BBStub3 - 22.10.2023 13:56

amazing piece of code

Ответить
@DevinRhode2
@DevinRhode2 - 15.08.2023 03:46

You failed Matt. These need to be validated at build time!!

Ответить
@marcoscarlomagno3065
@marcoscarlomagno3065 - 07.08.2023 00:46

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

Ответить
@CaioGuimaraes
@CaioGuimaraes - 04.08.2023 22:40

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

Ответить
@devxoo
@devxoo - 30.07.2023 19:56

Amazing!

Ответить
@gokudomatic
@gokudomatic - 29.07.2023 20:51

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

Ответить
@sankasanjeeva1182
@sankasanjeeva1182 - 27.07.2023 11:37

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

Ответить
@codefinity
@codefinity - 26.07.2023 03:06

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

Ответить
@jakub7048
@jakub7048 - 24.07.2023 19:53

only legends use the npm package called 'envalid'

Ответить
@jeffnikelson5824
@jeffnikelson5824 - 20.07.2023 10:34

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

Ответить
@codestalk9183
@codestalk9183 - 11.07.2023 18:33

this gives me ideas....

Ответить
@RyanWaite28
@RyanWaite28 - 10.07.2023 04:46

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'],
};
}

Ответить
@Riicardiinho16
@Riicardiinho16 - 09.07.2023 07:09

I'm using `env.d.ts` file to "Declare global ... " code, its okay?

Ответить
@Ked_gaming
@Ked_gaming - 08.07.2023 15:01

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 - 07.07.2023 12:00

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

Ответить
@johnswanson217
@johnswanson217 - 03.07.2023 05:27

This is just unecessary

Ответить
@souvlaki42
@souvlaki42 - 02.07.2023 21:14

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

Ответить
@wayneswildworld
@wayneswildworld - 01.07.2023 16:20

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

Ответить
@anhvuuc8693
@anhvuuc8693 - 01.07.2023 09:47

NO, I will use the global type define :s

Ответить
@danieltran7637
@danieltran7637 - 24.05.2023 16:38

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:

Ответить
@patriktrefil8338
@patriktrefil8338 - 18.05.2023 15:10

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>> {}`.

Ответить
@huynhthien4316
@huynhthien4316 - 06.05.2023 07:17

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.

Ответить
@some_user_880
@some_user_880 - 30.04.2023 22:47

So nice trick!

Ответить
@farahrayis5928
@farahrayis5928 - 28.04.2023 12:47

Incredible! And yes we love the short videos. Thanks

Ответить
@brangtoggez6363
@brangtoggez6363 - 26.04.2023 17:17

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

Ответить
@GrSurnov
@GrSurnov - 25.04.2023 22:50

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

Ответить
@hungify
@hungify - 23.04.2023 17:37

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

});

Ответить
@alexmalinin2387
@alexmalinin2387 - 22.04.2023 15:23

Awesome stuff!

Ответить
@Luxcium
@Luxcium - 22.04.2023 10:04

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

Ответить
@somebody656
@somebody656 - 22.04.2023 03:32

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

Ответить
@codinginflow
@codinginflow - 20.04.2023 13:07

I use the envalid package for this

Ответить
@LewisCowles
@LewisCowles - 20.04.2023 05:49

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

Ответить
@Mitsunee_
@Mitsunee_ - 19.04.2023 21:33

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

Ответить
@shahreazneeloy2119
@shahreazneeloy2119 - 19.04.2023 20:09

Ответить
@mikopiko
@mikopiko - 19.04.2023 19:09

I really don't get what zod offers over just plain TS?

Ответить
@CanRau
@CanRau - 19.04.2023 18:30

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

Ответить
@krumbo
@krumbo - 19.04.2023 14:54

Faaa who is this guy? Click straight SUBSCRIBE. I think the next big thing is to give devs some pro tips like this.

Ответить
@xypnox
@xypnox - 19.04.2023 14:30

Really appreciate the shorter format, yet clear explanations

Ответить
@xtinctspecies
@xtinctspecies - 19.04.2023 11:20

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

Ответить
@trapperxzw
@trapperxzw - 19.04.2023 10:53

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 ?

Ответить
@scottcallaway9586
@scottcallaway9586 - 19.04.2023 10:36

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

Ответить
@mathiasmaerker613
@mathiasmaerker613 - 19.04.2023 09:54

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

Ответить
@amir-ziaei
@amir-ziaei - 19.04.2023 09:27

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?

Ответить
@marcusradell7544
@marcusradell7544 - 19.04.2023 09:14

Global mutation 😬
Fine, it's just types and a runtime parse. But I would rather import the parsed config.

Ответить
@torickjdavis
@torickjdavis - 19.04.2023 08:22

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

Ответить
@austinkarren6755
@austinkarren6755 - 19.04.2023 07:17

This looks really familiar 🤔

Ответить