Package Exports
- @adonisjs/env
Readme
@adonisjs/env
Environment variables parser and validator used by the AdonisJS.
Note: This package is framework agnostic and can also be used outside of AdonisJS.
The @adonisjs/env package encapsulates the workflow around loading, parsing, and validating environment variables.
Setup
Install the package from the npm packages registry as follows.
npm i @adonisjs/env
yarn add @adonisjs/envEnvLoader
The EnvLoader class is responsible for loading the environment variable files from the disk and returning their contents as a string.
import { EnvLoader } from '@adonisjs/env'
const lookupPath = new URL('./', import.meta.url)
const loader = new EnvLoader(lookupPath)
const { envContents, currentEnvContents } = await loader.load()envContents
- The
envContentsis read from the.envfile from the root of thelookupPath. - No exceptions are raised if the
.envfile is missing. In brief, it is optional to have a.envfile. - If the
ENV_PATHenvironment variable is set, the loader will use that instead of the.envfile. This allows overwriting the location of the dot-env file.
currentEnvContents
- The
currentEnvContentscontents are read from the.env.[NODE_ENV]file. - If the current
NODE_ENV = 'development', then the contents of this variable will be from the.env.developmentfile and so on. - The contents of this file should take precendence over the
.envfile.
EnvParser
The EnvParser class is responsible for parsing the contents of the .env file(s) and converting them into an object.
import { EnvLoader, EnvParser } from '@adonisjs/env'
const lookupPath = new URL('./', import.meta.url)
const loader = new EnvLoader(lookupPath)
const { envContents, currentEnvContents } = await loader.load()
const envParser = new EnvParser(envContents)
const currentEnvParser = new EnvParser(currentEnvContents)
console.log(envParser.parse()) // { key: value }
console.log(currentEnvParser.parse()) // { key: value }The return value of parser.parse is an object with key-value pair. The parser also has support for interpolation.
You can also instruct the parser to prefer existing process.env values when they exist. When preferProcessEnv is set to true, the value from the env contents will be discarded in favor of existing process.env value.
new EnvParser(envContents, { preferProcessEnv: true })Validating environment variables
Once you have the parsed objects, you can optionally validate them against a pre-defined schema. We recommend validation for the following reasons.
- Fail early if one or more environment variables are missing.
- Cast values to specific data types.
- Have type safety alongside runtime safety.
import { Env } from '@adonisjs/env'
const validate = Env.rules({
PORT: Env.schema.number(),
HOST: Env.schema.string({ format: 'host' })
})The Env.schema is a reference to the @poppinss/validator-lite schema object. Make sure to go through the package README to view all the available methods and options.
The Env.rules method returns a function to validate the environment variables. The return value is the validated object with type information inferred from the schema.
validate(process.env)Following is a complete example of using the EnvLoader, EnvParser, and the validator to set up environment variables.
import { EnvLoader, EnvParser, Env } from '@adonisjs/env'
const lookupPath = new URL('./', import.meta.url)
const loader = new EnvLoader(lookupPath)
const { envContents, currentEnvContents } = await loader.load()
/**
* Loop over all the current env parsed values and let
* them take precedence over the existing process.env
* values.
*/
const currentEnvValues = new EnvParser(currentEnvContents).parse()
Object.keys(currentEnvValues).forEach((key) => {
process.env[key] = currentEnvValues[key]
})
const envValues = new EnvParser(envContents, { preferProcessEnv: true }).parse()
/**
* Loop over all the parsed env values and set
* them on "process.env"
*
* However, if the value already exists on "process.env", then
* do not overwrite it, instead update the envValues
* object.
*/
Object.keys(envValues).forEach((key) => {
if (process.env[key]) {
envValues[key] = process.env[key]
} else {
process.env[key] = envValues[key]
}
})
// Now perform the validation
const validate = Env.rules({
PORT: Env.schema.number(),
HOST: Env.schema.string({ format: 'host' })
})
const validated = validate({ ...envValues, ...currentEnvValues })
const env = new Env(validated)
env.get('PORT') // is a number
env.get('HOST') // is a string
env.get('NODE_ENV') // is unknown, hence a string or undefinedThe above code may seem like a lot of work to set up environment variables. However, you have fine-grained control over each step. In the case of AdonisJS, all this boilerplate is hidden inside the framework's application bootstrapping logic.