### Install @adonisjs/env Package Source: https://github.com/adonisjs/env/blob/7.x/README.md Install the package from the npm packages registry using npm. ```sh npm i @adonisjs/env ``` -------------------------------- ### Complete Example: Load and Validate Environment Variables Source: https://github.com/adonisjs/env/blob/7.x/README.md A complete example demonstrating how to create an Env instance, define a schema, and access validated environment variables. Existing process.env variables have the highest priority. ```ts import { Env } from '@adonisjs/env' const env = await Env.create(new URL('./', import.meta.url), { PORT: Env.schema.number(), HOST: Env.schema.string({ format: 'host' }) }) env.get('PORT') // is a number env.get('HOST') // is a string env.get('NODE_ENV') // is unknown, hence a string or undefined ``` -------------------------------- ### Example .env.example entry Source: https://github.com/adonisjs/env/blob/7.x/README.md This is an example of how a variable with an empty value is represented in the .env.example file. ```env SECRET_VARIABLE= ``` -------------------------------- ### Create Validated Environment Instance with Env.create Source: https://context7.com/adonisjs/env/llms.txt Use Env.create to load, parse, and validate environment variables against a schema. It returns a typed Env instance for safe access. Access unvalidated variables or provide default values using the get method. ```typescript import { Env } from '@adonisjs/env' // Create env instance with schema validation const env = await Env.create(new URL('./', import.meta.url), { PORT: Env.schema.number(), HOST: Env.schema.string({ format: 'host' }), APP_KEY: Env.schema.string(), CACHE_VIEWS: Env.schema.boolean(), DB_CONNECTION: Env.schema.enum(['mysql', 'pg', 'sqlite'] as const), REDIS_HOST: Env.schema.string.optional(), }) // Get values with full type safety const port = env.get('PORT') // type: number const host = env.get('HOST') // type: string const dbType = env.get('DB_CONNECTION') // type: 'mysql' | 'pg' | 'sqlite' const redisHost = env.get('REDIS_HOST') // type: string | undefined // Get unvalidated env vars (returns string | undefined) const nodeEnv = env.get('NODE_ENV') // Get with default value const logLevel = env.get('LOG_LEVEL', 'info') // type: string ``` -------------------------------- ### Get and Set Env Variables with Type Safety Source: https://context7.com/adonisjs/env/llms.txt Use the `Env.create` method to instantiate a validated environment instance. Access values using `env.get()` for type-safe retrieval and `env.set()` to modify them at runtime. Default values can be provided as a second argument to `env.get()`. ```typescript import { Env } from '@adonisjs/env' // Create validated env instance const env = await Env.create(new URL('./', import.meta.url), { PORT: Env.schema.number(), HOST: Env.schema.string(), DEBUG: Env.schema.boolean.optional(), }) // Get validated values (type-safe) const port = env.get('PORT') // type: number const host = env.get('HOST') // type: string const debug = env.get('DEBUG') // type: boolean | undefined // Get with default value const logLevel = env.get('LOG_LEVEL', 'info') // type: string const timeout = env.get('TIMEOUT', '5000') // type: string // Get unvalidated env vars (falls back to process.env) const nodeEnv = env.get('NODE_ENV') // type: string | undefined // Set values at runtime (updates both cache and process.env) env.set('PORT', 4000) console.log(env.get('PORT')) // 4000 console.log(process.env.PORT) // '4000' // Set unvalidated values env.set('CUSTOM_VAR', 'value') console.log(env.get('CUSTOM_VAR')) // 'value' ``` -------------------------------- ### Create and Save Env Editor Source: https://github.com/adonisjs/env/blob/7.x/README.md Initialize the Env editor and add new environment variables. Persist changes to disk using the save method. ```typescript import { EnvEditor } from '@adonisjs/env/editor' const editor = await EnvEditor.create(new URL('./', import.meta.url)) editor.add('PORT', 3000) editor.add('HOST', 'localhost') // Write changes on disk await editor.save() ``` -------------------------------- ### Add Empty Value to .env.example Source: https://github.com/adonisjs/env/blob/7.x/README.md Insert an empty value for a variable in the .env.example file by setting the third argument to true. ```typescript editor.add('SECRET_VARIABLE', 'secret-value', true) ``` -------------------------------- ### Load Environment Files with EnvLoader Source: https://context7.com/adonisjs/env/llms.txt The EnvLoader class loads environment files from disk in a priority order. It supports variants like .env.[NODE_ENV].local, .env.local, .env.[NODE_ENV], and .env. Optionally include .env.example files. ```typescript import { EnvLoader } from '@adonisjs/env' const loader = new EnvLoader(new URL('./', import.meta.url)) const envFiles = await loader.load() // Returns array of loaded files in priority order: // [ // { path: '/app/.env.development.local', contents: '...', fileExists: true }, // { path: '/app/.env.local', contents: '...', fileExists: false }, // { path: '/app/.env.development', contents: '...', fileExists: true }, // { path: '/app/.env', contents: '...', fileExists: true } // ] for (const file of envFiles) { if (file.fileExists) { console.log(`Loaded: ${file.path}`) console.log(`Contents: ${file.contents}`) } } // Load with .env.example file included const loaderWithExample = new EnvLoader(new URL('./', import.meta.url), true) const allFiles = await loaderWithExample.load() // Also includes { path: '/app/.env.example', ... } ``` -------------------------------- ### Load Environment Variable Files with EnvLoader Source: https://github.com/adonisjs/env/blob/7.x/README.md Use the EnvLoader class to load environment variable files from disk. The loader returns an array of objects, each containing the path and contents of a loaded file, ordered by priority. ```ts import { EnvLoader } from '@adonisjs/env' const lookupPath = new URL('./', import.meta.url) const loader = new EnvLoader(lookupPath) const envFiles = await loader.load() ``` -------------------------------- ### Custom Validation and Error Handling with Fallbacks Source: https://context7.com/adonisjs/env/llms.txt Use `Env.rules` for custom validation logic and implement `try-catch` blocks to gracefully handle validation errors. The `error.help` property can be parsed to display specific validation issues. ```typescript // Custom error handling with fallbacks const validator = Env.rules({ PORT: Env.schema.number(), HOST: Env.schema.string(), }) try { const validated = validator.validate({ PORT: 'not-a-number', HOST: undefined, }) } catch (error) { // Handle validation errors gracefully const lines = error.help.split('\n') for (const line of lines) { console.error(`[ENV ERROR] ${line}`) } } ``` -------------------------------- ### Define Validation Schema with Env.schema Source: https://github.com/adonisjs/env/blob/7.x/README.md Use Env.schema to define rules for validating environment variables, including data types and formats. This helps in failing early and casting values. ```ts import { Env } from '@adonisjs/env' const validator = Env.rules({ PORT: Env.schema.number(), HOST: Env.schema.string({ format: 'host' }) }) ``` -------------------------------- ### Define Validation Schema with Env.rules Source: https://context7.com/adonisjs/env/llms.txt Use Env.rules to create a validator for environment variables against a schema. Supports strings, numbers, booleans, enums, and custom formats. Optional and secret values can also be defined. Validation errors provide detailed help messages. ```typescript import { Env } from '@adonisjs/env' // Define validation schema const validator = Env.rules({ // Required string APP_NAME: Env.schema.string(), // String with format validation HOST: Env.schema.string({ format: 'host' }), APP_URL: Env.schema.string({ format: 'url' }), // Required number PORT: Env.schema.number(), // Required boolean (accepts '1', 'true', 'on', 'yes') CACHE_VIEWS: Env.schema.boolean(), // Enum with specific values NODE_ENV: Env.schema.enum(['development', 'production', 'test'] as const), // Optional values DEBUG: Env.schema.boolean.optional(), REDIS_PORT: Env.schema.number.optional(), // Secret values (wrapped in Secret class for protection) DB_PASSWORD: Env.schema.secret(), API_KEY: Env.schema.secret.optional(), }) // Validate against process.env try { const validated = validator.validate(process.env) console.log(validated.PORT) // type: number console.log(validated.NODE_ENV) // type: 'development' | 'production' | 'test' } catch (error) { console.error('Validation failed:', error.message) console.error('Details:', error.help) // Output: // Validation failed: Validation failed for one or more environment variables // Details: // - Missing environment variable "APP_NAME" // - Value for environment variable "PORT" must be numeric } ``` -------------------------------- ### Handle Invalid Environment Variables with E_INVALID_ENV_VARIABLES Source: https://context7.com/adonisjs/env/llms.txt Catch `E_INVALID_ENV_VARIABLES` errors thrown by `Env.create` to handle validation failures. The error object includes a `help` property with detailed messages about missing or invalid variables, aiding in debugging. ```typescript import { Env, errors } from '@adonisjs/env' async function bootstrap() { try { const env = await Env.create(new URL('./', import.meta.url), { PORT: Env.schema.number(), HOST: Env.schema.string({ format: 'host' }), APP_KEY: Env.schema.schema.string(), DB_CONNECTION: Env.schema.enum(['mysql', 'pg', 'sqlite'] as const), }) return env } catch (error) { if (error instanceof errors.E_INVALID_ENV_VARIABLES) { console.error('Environment validation failed!') console.error(error.message) // "Validation failed for one or more environment variables" console.error('Details:') console.error(error.help) // - Missing environment variable "APP_KEY" // - Value for environment variable "PORT" must be numeric // - Value for environment variable "DB_CONNECTION" must be one of mysql, pg, sqlite process.exit(1) } throw error } } ``` -------------------------------- ### Parse Environment Strings with EnvParser Source: https://context7.com/adonisjs/env/llms.txt Use EnvParser to parse environment variable strings, supporting interpolation, escape sequences, and ignoring process.env values. ```typescript import { EnvParser } from '@adonisjs/env' // Basic parsing with interpolation const parser = new EnvParser(` PORT=3000 HOST=localhost APP_URL=http://$HOST:$PORT REDIS_PORT=${PORT} ESCAPED=foo\\$bar `, new URL('./', import.meta.url)) const values = await parser.parse() console.log(values) // { // PORT: '3000', // HOST: 'localhost', // APP_URL: 'http://localhost:3000', // REDIS_PORT: '3000', // ESCAPED: 'foo$bar' // } // Ignore existing process.env values const isolatedParser = new EnvParser(` PORT=4000 `, new URL('./', import.meta.url), { ignoreProcessEnv: true }) const isolated = await isolatedParser.parse() console.log(isolated.PORT) // '4000' (even if process.env.PORT exists) ``` -------------------------------- ### Edit Environment Files with EnvEditor Source: https://context7.com/adonisjs/env/llms.txt Use EnvEditor to programmatically add or modify environment variables in .env and .env.example files and persist changes to disk. It supports adding variables with empty values for secrets. ```typescript import { EnvEditor } from '@adonisjs/env/editor' // Create editor and load existing files const editor = await EnvEditor.create(new URL('./', import.meta.url)) // Add new environment variables editor.add('PORT', 3000) editor.add('HOST', 'localhost') editor.add('DEBUG', true) // Add with empty value in .env.example (for secrets) editor.add('DB_PASSWORD', 'supersecret', true) // .env gets: DB_PASSWORD=supersecret // .env.example gets: DB_PASSWORD= // Inspect changes before saving const files = editor.toJSON() for (const file of files) { console.log(`File: ${file.path}`) console.log(`Contents:\n${file.contents.join('\n')}`) } // Persist changes to disk await editor.save() // Example: Programmatically configure app on first run async function configureApp() { const editor = await EnvEditor.create(new URL('./', import.meta.url)) // Generate random app key const appKey = crypto.randomBytes(32).toString('base64') editor.add('APP_KEY', appKey, true) // Set default database configuration editor.add('DB_CONNECTION', 'pg') editor.add('DB_HOST', '127.0.0.1') editor.add('DB_PORT', 5432) editor.add('DB_DATABASE', 'myapp') editor.add('DB_USER', 'postgres', true) editor.add('DB_PASSWORD', '', true) await editor.save() console.log('Environment configured successfully') } ``` -------------------------------- ### Validate Environment Variables Source: https://github.com/adonisjs/env/blob/7.x/README.md Call the validate method on the validator instance created by Env.rules to validate the process.env object against the defined schema. ```ts validator.validate(process.env) ``` -------------------------------- ### Handle Invalid Env Variables Exception Source: https://github.com/adonisjs/env/blob/7.x/README.md Catch and log detailed error messages for the E_INVALID_ENV_VARIABLES exception using the error.cause property. ```typescript try { validate(envValues) } catch (error) { console.log(error.cause) } ``` -------------------------------- ### Parse .env File Contents with EnvParser Source: https://github.com/adonisjs/env/blob/7.x/README.md The EnvParser class parses the contents of .env files into a JavaScript object. It supports interpolation and can optionally ignore existing process.env values. ```ts import { EnvParser } from '@adonisjs/env' const envParser = new EnvParser(` PORT=3000 HOST=localhost `) console.log(await envParser.parse()) // { PORT: '3000', HOST: 'localhost' } ``` ```ts new EnvParser(envContents, { ignoreProcessEnv: true }) ``` -------------------------------- ### Define Custom Secret Identifiers with EnvParser Source: https://context7.com/adonisjs/env/llms.txt Register custom identifiers for EnvParser to load environment values from external sources like Docker Secrets or HashiCorp Vault. The identifier callback can perform asynchronous operations. ```typescript import { readFile } from 'node:fs/promises' import { EnvParser } from '@adonisjs/env' // Register custom identifier for Docker secrets EnvParser.defineIdentifier('docker-secret', async (value) => { const secretPath = `/run/secrets/${value}` return await readFile(secretPath, 'utf-8') }) // Register identifier for HashiCorp Vault EnvParser.defineIdentifier('vault', async (value) => { const [path, key] = value.split('#') const response = await fetch(`https://vault.example.com/v1/${path}`) const data = await response.json() return data.data[key] }) // Use in .env file: // DB_PASSWORD=docker-secret:db_password // API_KEY=vault:secret/data/myapp#api_key const parser = new EnvParser(` DB_PASSWORD=docker-secret:db_password API_KEY=vault:secret/data/myapp#api_key REGULAR_VAR=hello `, new URL('./', import.meta.url)) const values = await parser.parse() // DB_PASSWORD: content from /run/secrets/db_password // API_KEY: value from Vault at secret/data/myapp // Built-in 'file' identifier (reads from file relative to app root) const fileParser = new EnvParser(` SSL_CERT=file:./certs/server.crt SSL_KEY=file:./certs/server.key `, new URL('./', import.meta.url)) // Remove identifier when no longer needed EnvParser.removeIdentifier('vault') // Define only if not already registered EnvParser.defineIdentifierIfMissing('file', async (value) => { // Won't override built-in 'file' identifier return value }) ``` -------------------------------- ### Define Custom Identifier for Interpolation Source: https://github.com/adonisjs/env/blob/7.x/README.md Register a custom identifier function with EnvParser to handle specific interpolation patterns, such as reading values from files. ```ts import { readFile } from 'node:fs/promises' import { EnvParser } from '@adonisjs/env' EnvParser.identifier('file', (value) => { return readFile(value, 'utf-8') }) const envParser = new EnvParser(` DB_PASSWORD=file:/run/secret/db_password `) console.log(await envParser.parse()) // { DB_PASSWORD: 'Value from file /run/secret/db_password' } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.