Skip to content

environmentVariable

Loads, expands, and validates environment variables. This version returns an Either result. If you prefer throwing behavior, use environmentVariableOrThrow.

Example

ts
import { 
environmentVariable
} from "@duplojs/server-utils";
import {
DP
,
E
,
unwrap
} from "@duplojs/utils";
const
firstResult
= await
environmentVariable
({
APPLICATION_NAME
:
DP
.
string
(),
}); // firstResult: E.Success<{ APPLICATION_NAME: string }> | E.Left<unknown> if (
E
.
isRight
(
firstResult
)) {
const
parsedVariables
=
unwrap
(
firstResult
);
// parsedVariables.APPLICATION_NAME: string } const
secondResult
= await
environmentVariable
(
{
APPLICATION_NAME
:
DP
.
string
(),
API_URL
:
DP
.
string
(),
}, {
paths
: [".env", ".env.local"],
override
: true,
justRead
: true,
}, ); // secondResult: E.Success<{ APPLICATION_NAME: string; API_URL: string }> | E.Left<unknown>

Other examples

Throw variant

ts
import { 
environmentVariableOrThrow
} from "@duplojs/server-utils";
import {
DP
} from "@duplojs/utils";
const
parsedVariables
= await
environmentVariableOrThrow
(
{
APPLICATION_NAME
:
DP
.
string
(),
APPLICATION_PORT
:
DP
.
number
(),
}, {
paths
: [".env"],
override
: false,
justRead
: true,
}, ); // parsedVariables: { APPLICATION_NAME: string; APPLICATION_PORT: number }

Syntax

typescript
function environmentVariable<
	GenericShape extends DP.DataParserObjectShape
>(
  shape: GenericShape,
  params?: EnvironmentVariableParams
): Promise<
  | E.Success<DP.DataParserObjectShapeOutput<GenericShape>>
  | FileSystemLeft<"read-text-file">
  | E.Error<DP.DataParserError>
>

Parameters

  • shape (GenericShape) : schema used to parse and validate environment variables.
  • params (EnvironmentVariableParams, optional) : behavior options.
  • params.paths (string[], optional) : env file paths to read.
  • params.override (boolean, default false) : allows file values to replace existing runtime values.
  • params.justRead (boolean, default false) : reads and validates without writing back to runtime environment variables.

Return value

  • E.Success<DP.DataParserObjectShapeOutput<GenericShape>> : parsed variables that match the schema.
  • FileSystemLeft<"read-text-file"> : if reading an env file fails.
  • E.Error<DP.DataParserError> : if schema validation fails.

See also

Released under the MIT license.