Package Exports
- 12factor-env
- 12factor-env/esm/index.js
- 12factor-env/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (12factor-env) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
12factor-env
Environment variable validation with secret file support for 12-factor apps
A TypeScript library for validating environment variables with built-in support for Docker/Kubernetes secret files. Built on top of envalid with additional features for reading secrets from files.
Installation
npm install 12factor-envUsage
import { env, str, num, bool, port, email, host } from '12factor-env';
const config = env(
process.env,
{
// Required environment variables
DATABASE_URL: str(),
API_KEY: str()
},
{
// Optional environment variables with defaults
PORT: port({ default: 3000 }),
DEBUG: bool({ default: false }),
LOG_LEVEL: str({ default: 'info' })
}
);
console.log(config.DATABASE_URL); // Validated string
console.log(config.PORT); // Validated numberSecret File Support
This library supports reading secrets from files, which is useful for Docker secrets and Kubernetes secrets that are mounted as files.
Direct Secret Files
Secrets can be read from /run/secrets/ (or a custom path via ENV_SECRETS_PATH):
import { env, str } from '12factor-env';
// If /run/secrets/DATABASE_PASSWORD exists, it will be read automatically
const config = env(process.env, {
DATABASE_PASSWORD: str()
});_FILE Suffix Pattern
You can also use the _FILE suffix pattern commonly used with Docker:
# Set the path to the secret file
export DATABASE_PASSWORD_FILE=/run/secrets/db-passwordimport { env, str } from '12factor-env';
// Will read from the file specified in DATABASE_PASSWORD_FILE
const config = env(process.env, {
DATABASE_PASSWORD: str()
});Custom Secrets Path
Set ENV_SECRETS_PATH to change the default secrets directory:
export ENV_SECRETS_PATH=/custom/secrets/pathValidators
All validators from envalid are re-exported:
| Validator | Description |
|---|---|
str() |
String value |
bool() |
Boolean (true, false, 1, 0) |
num() |
Number |
port() |
Port number (1-65535) |
host() |
Hostname or IP address |
url() |
Valid URL |
email() |
Valid email address |
json() |
JSON string (parsed) |
Validator Options
All validators accept options:
import { str, num } from '12factor-env';
const config = env(process.env, {
API_KEY: str({ desc: 'API key for external service' }),
TIMEOUT: num({ default: 5000, desc: 'Request timeout in ms' })
});API
env(inputEnv, secrets, vars)
Main function to validate environment variables.
inputEnv- The environment object (usuallyprocess.env)secrets- Required environment variablesvars- Optional environment variables
secret(envFile)
Create a validator for a secret file:
import { env, secret } from '12factor-env';
const config = env(process.env, {
DB_PASSWORD: secret('DATABASE_PASSWORD')
});getSecret(name)
Read a secret from a file:
import { getSecret } from '12factor-env';
const password = getSecret('DATABASE_PASSWORD');secretPath(name)
Resolve the full path to a secret file:
import { secretPath } from '12factor-env';
const path = secretPath('DATABASE_PASSWORD');
// Returns: /run/secrets/DATABASE_PASSWORDRe-exports from envalid
The following are re-exported from envalid for convenience:
cleanEnv- Low-level env cleaning functionmakeValidator- Create custom validatorsEnvError- Error class for validation errorsEnvMissingError- Error class for missing required varstestOnly- Helper for test-only defaults
Education and Tutorials
🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.
📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.
🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
⚡ Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
🔧 Troubleshooting Common issues and solutions for pgpm, PostgreSQL, and testing.
Related Constructive Tooling
📦 Package Management
- pgpm: 🖥️ PostgreSQL Package Manager for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
🧪 Testing
- pgsql-test: 📊 Isolated testing environments with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
- pgsql-seed: 🌱 PostgreSQL seeding utilities for CSV, JSON, SQL data loading, and pgpm deployment.
- supabase-test: 🧪 Supabase-native test harness preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
- graphile-test: 🔐 Authentication mocking for Graphile-focused test helpers and emulating row-level security contexts.
- pg-query-context: 🔒 Session context injection to add session-local context (e.g.,
SET LOCAL) into queries—ideal for settingrole,jwt.claims, and other session settings.
🧠 Parsing & AST
- pgsql-parser: 🔄 SQL conversion engine that interprets and converts PostgreSQL syntax.
- libpg-query-node: 🌉 Node.js bindings for
libpg_query, converting SQL into parse trees. - pg-proto-parser: 📦 Protobuf parser for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
- @pgsql/enums: 🏷️ TypeScript enums for PostgreSQL AST for safe and ergonomic parsing logic.
- @pgsql/types: 📝 Type definitions for PostgreSQL AST nodes in TypeScript.
- @pgsql/utils: 🛠️ AST utilities for constructing and transforming PostgreSQL syntax trees.
Credits
🛠 Built by the Constructive team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on GitHub.
Disclaimer
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.