znv
znv copied to clipboard
Support for Name Mapping
I'm going to be using this for the web and many bundlers/frameworks enforce a prefix for web available environmental variables. This is something like NEXT_PUBLIC_API_URL
or VITE_API_URL
. I would love if this had first class support to remove prefixes from what I pass in.
I understand if it's not part of the lib, but wanted to open an issue to chat about it. Thanks for a great lib!
Thanks for the kind words! The recommended way to perform name mapping is like this:
export const {
NEXT_PUBLIC_API_URL: PUBLIC_API_URL,
SOME_OTHER_PROPERTY,
A_THIRD_THING: MY_COOL_RENAMED_VALUE,
} = parseEnv(process.env, {
NEXT_PUBLIC_API_URL: z.string().min(1),
SOME_OTHER_PROPERTY: z.number().int().positive(),
A_THIRD_THING: z.enum(["red", "blue"]),
});
I can't think of a much more idiomatic way of doing this, personally... I guess if you're using the detailed spec declaration format there could be a field like renameTo
-- but handling that would add a lot of complexity to the type inference and I'm not really convinced it's worth it.
Incidentally, note that you won't be able to pass in process.env
at all if your framework or bundler inlines secrets, like Next does for server-side secrets:
Note: In order to keep server-only secrets safe, environment variables are evaluated at build time, so only environment variables actually used will be included. This means that
process.env
is not a standard JavaScript object, so you’re not able to use object destructuring. Environment variables must be referenced as e.g.process.env.PUBLISHABLE_KEY
, notconst { PUBLISHABLE_KEY } = process.env
.