- Notifications
You must be signed in to change notification settings - Fork12
Framework agnostic environment variables parser and validator
License
adonisjs/env
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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.
Install the package from the npm packages registry as follows.
npm i @adonisjs/env
TheEnvLoader
class is responsible for loading the environment variable files from the disk and returning their contents as a string.
import{EnvLoader}from'@adonisjs/env'constlookupPath=newURL('./',import.meta.url)constloader=newEnvLoader(lookupPath)constenvFiles=awaitloader.load()
The return value is an array of objects with following properties.
path
: The path to the loaded dot-env file.contents
: The contents of the file.
Following is the list of loaded files. The array is ordered by the priority of the files. The first file has the highest priority and must override the variables from the last file.
Priority | File name | Environment | Should I.gitignore it | Notes |
---|---|---|---|---|
1st | .env.[NODE_ENV].local | Current environment | Yes | Loaded whenNODE_ENV is set |
2nd | .env.local | All | Yes | Loaded in all the environments excepttest ortesting environments |
3rd | .env.[NODE_ENV] | Current environment | No | Loaded whenNODE_ENV is set |
4th | .env | All | Depends | Loaded in all the environments. You should.gitignore it when storing secrets in this file |
TheEnvParser
class is responsible for parsing the contents of the.env
file(s) and converting them into an object.
import{EnvParser}from'@adonisjs/env'constenvParser=newEnvParser(` PORT=3000 HOST=localhost`)console.log(awaitenvParser.parse())// { PORT: '3000', HOST: 'localhost' }
The return value ofparser.parse
is an object with key-value pair. The parser also has support for interpolation.
By default, the parser prefers existingprocess.env
values when they exist. However, you can instruct the parser to ignore existingprocess.env
files as follows.
newEnvParser(envContents,{ignoreProcessEnv:true})
You can define an "identifier" to be used for interpolation. The identifier is a string that prefix the environment variable value and let you customize the value resolution.
import{readFile}from'node:fs/promises'import{EnvParser}from'@adonisjs/env'EnvParser.identifier('file',(value)=>{returnreadFile(value,'utf-8')})constenvParser=newEnvParser(` DB_PASSWORD=file:/run/secret/db_password`)console.log(awaitenvParser.parse())// { DB_PASSWORD: 'Value from file /run/secret/db_password' }
This can be useful when you are using secrets manager likeDocker Secret
,HashiCorp Vault
,Google Secrets Manager
and others to manage your secrets.
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'constvalidator=Env.rules({PORT:Env.schema.number(),HOST:Env.schema.string({format:'host'})})
TheEnv.schema
is a reference to the@poppinss/validator-liteschema
object. Make sure to go through the package README to view all the available methods and options.
TheEnv.rules
method returns an instance of the validator to validate the environment variables. The return value is the validated object with type information inferred from the schema.
validator.validate(process.env)
Following is a complete example of loading dot-env files and validating them in one go.
Note: Existing
process.env
variables have the top most priority over the variables defined in any of the files.
import{Env}from'@adonisjs/env'constenv=awaitEnv.create(newURL('./',import.meta.url),{PORT:Env.schema.number(),HOST:Env.schema.string({format:'host'})})env.get('PORT')// is a numberenv.get('HOST')// is a stringenv.get('NODE_ENV')// is unknown, hence a string or undefined
The Env editor can be used to edit dot-env files and persist changes on disk. Only the.env
and.env.example
files are updated (if exists).
import{EnvEditor}from'@adonisjs/env/editor'consteditor=awaitEnvEditor.create(newURL('./',import.meta.url))editor.add('PORT',3000)editor.add('HOST','localhost')// Write changes on diskawaiteditor.save()
You can also insert an empty value for the.env.example
file by setting the last argument totrue
.
editor.add('SECRET_VARIABLE','secret-value',true)
This will add the following line to the.env.example
file.
SECRET_VARIABLE=
The exception is raised during environment variables validation exception. The exception is raised withValidation failed for one or more environment variables
message.
You can access the detailed error messages using theerror.cause
property.
try{validate(envValues)}catch(error){console.log(error.cause)}
About
Framework agnostic environment variables parser and validator