API Reference

Complete API documentation for @redenv/client.

ClassDescription
RedenvMain client for loading and writing secrets
SecretsContainer returned by load() with helper methods
SecretValueWrapper for type casting via get()
RedenvErrorCustom error class with error codes

Redenv Class#

The main client for interacting with Redenv.

Constructor#

import { Redenv } from "@redenv/client";

const redenv = new Redenv(options: RedenvOptions);

RedenvOptions

PropertyTypeRequiredDefaultDescription
projectstringYesProject name
tokenIdstringYesService Token public ID (stk_...)
tokenstringYesService Token secret key (redenv_sk_...)
upstash.urlstringYesUpstash Redis REST URL
upstash.tokenstringYesUpstash Redis REST token
environmentstringNo"development"Environment name
cache.ttlnumberNo300Seconds before cache is stale
cache.swrnumberNo86400Stale-while-revalidate window (seconds)
env.overridebooleanNotrueOverwrite existing process.env vars
log"none" | "low" | "high"No"low"Logging verbosity

init()#

Initialize the client, populate process.env, and return secrets for validation.

init(): Promise<Secrets>
const secrets = await redenv.init();
secrets.require("DATABASE_URL"); // Validate at startup

load()#

Fetch, decrypt, cache, and return secrets.

load(): Promise<Secrets>
const secrets = await redenv.load();
console.log(secrets.API_KEY);

Info

init() and load() are identical. Use init() at startup, load() everywhere else for semantic clarity.


set()#

Add or update a secret. Requires a read/write Service Token.

set(key: string, value: string): Promise<void>
ParameterTypeDescription
keystringSecret key name
valuestringSecret value
await redenv.set("LOG_LEVEL", "debug");

getVersion()#

Fetch a specific version of a secret (time travel).

getVersion(
  key: string,
  version: number,
  mode?: "id" | "index"
): Promise<string | undefined>
ParameterTypeDefaultDescription
keystringSecret key name
versionnumberVersion ID or index
mode"id" | "index""id"Lookup mode
// By version ID
const v5 = await redenv.getVersion("API_KEY", 5);

// By index (0 = latest, 1 = previous, ...)
const previous = await redenv.getVersion("API_KEY", 1, "index");

Secrets Class#

Returned by load() and init(). Provides enhanced access to secrets.

Property Access#

Access secrets directly as properties:

const secrets = await redenv.load();

secrets.API_KEY;      // string
secrets.DATABASE_URL; // string
secrets["MY-KEY"];    // string (for keys with special chars)

get()#

Get a secret with optional default value and type-casting.

get(key: string, defaultValue?: any): SecretValue
secrets.get("PORT", 3000).toInt();    // number
secrets.get("DEBUG", false).toBool(); // boolean
secrets.get("CONFIG").toJSON();       // parsed JSON

require()#

Validate that secrets exist. Throws RedenvError if any are missing.

require(...keys: string[]): this
secrets.require("DATABASE_URL", "JWT_SECRET", "STRIPE_KEY");
// Throws: RedenvError: Missing required secrets: JWT_SECRET

Returns this for chaining:

const dbUrl = secrets.require("DATABASE_URL").DATABASE_URL;

scope()#

Create a subset with only prefixed keys (prefix is removed).

scope(prefix: string): Secrets
// Secrets: AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGION, OTHER_VAR

const aws = secrets.scope("AWS_");
aws.ACCESS_KEY; // AWS_ACCESS_KEY value
aws.SECRET_KEY; // AWS_SECRET_KEY value
aws.REGION;     // AWS_REGION value
// OTHER_VAR not included

raw#

Access unexpanded values (with ${VAR} syntax preserved).

get raw(): Secrets
// If AUTH_URL = "${BASE_URL}/auth"

secrets.AUTH_URL;     // "https://api.example.com/auth"
secrets.raw.AUTH_URL; // "${BASE_URL}/auth"

toObject()#

Get all secrets as a plain object (unmasked).

toObject(): Record<string, string>
const obj = secrets.toObject();
// { API_KEY: "sk_live_...", DATABASE_URL: "postgres://..." }

toString()#

Get masked string representation (safe for logging).

toString(): string
console.log(secrets.toString());
// Secrets { "API_KEY": "********", "DATABASE_URL": "********" }

toJSON()#

Get masked object (used by JSON.stringify).

toJSON(): Record<string, string>
console.log(JSON.stringify(secrets));
// {"API_KEY":"********","DATABASE_URL":"********"}

SecretValue Class#

Returned by secrets.get(). Provides type conversion methods.

toString()#

toString(): string

Returns the raw string value.


toInt()#

toInt(): number | undefined

Parse as integer. Returns undefined if not a valid number.

secrets.get("PORT", 3000).toInt(); // 3000

toBool()#

toBool(): boolean | undefined

Parse as boolean. Returns undefined if not a recognized value.

Truthy valuesFalsy values
"true", "1", "yes", "on", "t""false", "0", "no", "off", "f"
secrets.get("DEBUG").toBool();     // true/false
secrets.get("ENABLED", true).toBool(); // with default

toJSON()#

toJSON<T = any>(): T | undefined

Parse as JSON. Returns undefined if invalid JSON.

secrets.get("APP_CONFIG").toJSON<{ theme: string }>();

RedenvError#

Custom error class for Redenv-specific errors.

import { RedenvError } from "@redenv/client";

class RedenvError extends Error {
  code: string;
  message: string;
}

Error Codes#

CodeDescription
MISSING_CONFIGRequired configuration options missing
PROJECT_NOT_FOUNDProject doesn't exist in Redis
INVALID_TOKEN_IDService Token ID not found
INVALID_TOKENService Token secret key invalid
SECRET_NOT_FOUNDRequested secret key doesn't exist
DECRYPTION_FAILEDFailed to decrypt (wrong password/token)
PERMISSION_DENIEDToken lacks required permissions
UNKNOWN_ERRORUnexpected error

Example#

import { RedenvError } from "@redenv/client";

try {
  const secrets = await redenv.load();
  secrets.require("MISSING_KEY");
} catch (error) {
  if (error instanceof RedenvError) {
    console.error(`[${error.code}] ${error.message}`);
    // [SECRET_NOT_FOUND] Missing required secrets: MISSING_KEY
  }
}

TypeScript Types#

All types are exported from @redenv/client:

import type {
  RedenvOptions,
  Secrets,
  SecretValue,
  RedenvError,
} from "@redenv/client";

Low-Level Utilities#

For advanced use cases (building custom clients, etc.):

import {
  fetchAndDecrypt,
  setSecret,
  deleteSecret,
  getPEK,
  populateEnv,
  getSecretHistory,
  decryptVersion,
} from "@redenv/client/utils";
FunctionDescription
getPEK(redis, options)Fetch and decrypt Project Encryption Key
fetchAndDecrypt(redis, options, pek?)Fetch and decrypt all secrets
setSecret(redis, options, key, value, pek?)Write a secret
deleteSecret(redis, options, key, pek?)Delete a secret
populateEnv(secrets, options)Inject secrets into process.env
getSecretHistory(redis, options, key)Get version history for a key
decryptVersion(redis, options, value, pek?)Decrypt a specific version

Warning

These are internal APIs and may change between versions. Use the Redenv class for stable APIs.