@mvdlei/env
The @mvdlei/env
package provides a utility function define
for defining and validating environment variables in TypeScript using the Zod schema.
Installation
Dependencies
The @mvdlei/env
package depends on the following packages:
zod
Usages
Usage Env
This package is usable in React and Node.
But be aware to set your source
property correctly, with vite
you should use import.meta.env
and with next
you should use process.env
.
Example
With options
Strict mode
And where you want to use the environment variable, you can use the get
method with a default value.
Usage Env.set
Strict mode
Usage define
This package is usable in React and Node.
But be aware to set your source
property correctly, with vite
you should use import.meta.env
and with next
you should use process.env
.
Example
An example as used in the showcase
app (here).
API Reference
Env
The Env
class provides a set of utility methods for working with environment variables.
init(options: EnvOptions): Env
The init
method is used to initialize a new Env
instance with the provided options.
get(key: string, defaultValue?: Primitive): Primitive
The get
method is used to get the value of an environment variable by key.
set(key: string, value: Primitive): void
The set
method is used to set the value of an environment variable by key.
EnvOptions
The EnvOptions
interface defines the contract for the Env
class options.
Default values, providing one will override its default counterpart.
define(options: EnvOptions<TPrefix, TPrefixed, TEnv>): Readonly<z.infer<ZodObject<TPrefixed>> & z.infer<ZodObject<TEnv>>>
The define
function is used to define and validate environment variables based on the provided options.
Options
env
: An object representing the schema for general environment variables.prefix
: A prefix for client-side variables.prefixed
: An object representing the schema for client-side environment variables.isClient
: A boolean indicating whether the app is running on the client (default:typeof window !== "undefined"
).onValidationError
: A callback function called when validation fails.onInvalidAccess
: A callback function called when a server-side environment variable is accessed on the client.validate
: A boolean indicating whether to skip validation of environment variables (default:false
).emptyStringAsUndefined
: A boolean indicating whether to treat empty strings asundefined
(default:false
).strict
: An object representing the schema for strict runtime environment variables.runtime
: Runtime environment variables to use for validation.source
: Be aware that this is where the environment variables are read from. So usingprocess.env
will not work in the browser.