What is env-schema?
The env-schema npm package is used to validate environment variables against a schema. It ensures that the environment variables are present and conform to the expected types and constraints, providing a robust way to manage configuration in Node.js applications.
What are env-schema's main functionalities?
Schema Validation
This feature allows you to define a schema for your environment variables and validate them. The code sample demonstrates how to define a schema with required properties and default values, and then validate the environment variables against this schema.
const envSchema = require('env-schema');
const schema = {
type: 'object',
required: ['PORT', 'HOST'],
properties: {
PORT: {
type: 'number',
default: 3000
},
HOST: {
type: 'string',
default: 'localhost'
}
}
};
const config = envSchema({ schema: schema });
console.log(config);
Default Values
This feature allows you to specify default values for environment variables. If the environment variable is not set, the default value will be used. The code sample shows how to set default values for the PORT and HOST environment variables.
const envSchema = require('env-schema');
const schema = {
type: 'object',
properties: {
PORT: {
type: 'number',
default: 3000
},
HOST: {
type: 'string',
default: 'localhost'
}
}
};
const config = envSchema({ schema: schema });
console.log(config);
Type Coercion
This feature allows you to coerce environment variables to the specified types. The code sample demonstrates how to coerce the PORT environment variable to a number and the DEBUG environment variable to a boolean.
const envSchema = require('env-schema');
const schema = {
type: 'object',
properties: {
PORT: {
type: 'number'
},
DEBUG: {
type: 'boolean'
}
}
};
process.env.PORT = '3000';
process.env.DEBUG = 'true';
const config = envSchema({ schema: schema });
console.log(config);
Other packages similar to env-schema
joi
Joi is a powerful schema description language and data validator for JavaScript. It can be used to validate environment variables, but it is more general-purpose and can validate any JavaScript object. Compared to env-schema, Joi offers more flexibility and a richer set of validation features, but it requires more setup for environment variable validation.
dotenv
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. While it does not provide schema validation, it is often used in conjunction with validation libraries like Joi or env-schema to manage environment variables in Node.js applications.
convict
Convict is a configuration management tool for Node.js that allows you to define a schema for your configuration, including environment variables. It provides validation, default values, and type coercion similar to env-schema, but it also includes features for managing configuration files and command-line arguments.
env-schema
Utility to check environment variables using JSON schema, Ajv, and
dotenv.
See supporting resources section for helpful guides on getting started.
Install
npm i env-schema
Usage
const envSchema = require('env-schema')
const schema = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema({
schema: schema,
data: data,
dotenv: true
})
console.log(config)
see DotenvConfigOptions
Custom ajv instance
Optionally, the user can supply their own ajv instance:
const envSchema = require('env-schema')
const Ajv = require('ajv')
const schema = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema({
schema: schema,
data: data,
dotenv: true,
ajv: new Ajv({
allErrors: true,
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
allowUnionTypes: true
})
})
console.log(config)
It is possible to enhance the default ajv instance providing the customOptions
function parameter.
This example shows how to use the format
keyword in your schemas.
const config = envSchema({
schema: schema,
data: data,
dotenv: true,
ajv: {
customOptions (ajvInstance) {
require('ajv-formats')(ajvInstance)
return ajvInstance
}
}
})
Note that it is mandatory returning the ajv instance.
Order of configuration loading
The order of precedence for configuration data is as follows, from least
significant to most:
- Data sourced from
.env
file (when dotenv
configuration option is set) - Data sourced from environment variables in
process.env
- Data provided via the
data
configuration option
Fluent-Schema API
It is also possible to use fluent-json-schema:
const envSchema = require('env-schema')
const S = require('fluent-json-schema')
const config = envSchema({
schema: S.object().prop('PORT', S.number().default(3000).required()),
data: data,
dotenv: true,
expandEnv: true,
})
console.log(config)
NB Support for additional properties in the schema is disabled for this plugin, with the additionalProperties
flag set to false
internally.
Custom keywords
This library supports the following Ajv custom keywords:
separator
Type: string
Applies to type: string
When present, the provided schema value will be split on this value.
Example:
const envSchema = require('env-schema')
const schema = {
type: 'object',
required: [ 'ALLOWED_HOSTS' ],
properties: {
ALLOWED_HOSTS: {
type: 'string',
separator: ','
}
}
}
const data = {
ALLOWED_HOSTS: '127.0.0.1,0.0.0.0'
}
const config = envSchema({
schema: schema,
data: data,
dotenv: true
})
The ajv keyword definition objects can be accessed through the property keywords
on the envSchema
function:
const envSchema = require('env-schema')
const Ajv = require('ajv')
const schema = {
type: 'object',
properties: {
names: {
type: 'string',
separator: ','
}
}
}
const config = envSchema({
schema: schema,
data: data,
dotenv: true,
ajv: new Ajv({
allErrors: true,
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
allowUnionTypes: true,
keywords: [envSchema.keywords.separator]
})
})
console.log(config)
TypeScript
You can specify the type of your config
:
import { envSchema, JSONSchemaType } from 'env-schema'
interface Env {
PORT: number;
}
const schema: JSONSchemaType<Env> = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema({
schema
})
You can also use a JSON Schema
library like typebox
:
import { envSchema } from 'env-schema'
import { Static, Type } from '@sinclair/typebox'
const schema = Type.Object({
PORT: Type.Number({ default: 3000 })
})
type Schema = Static<typeof schema>
const config = envSchema<Schema>({
schema
})
If no type is specified the config
will have the EnvSchemaData
type.
export type EnvSchemaData = {
[key: string]: unknown;
}
Supporting resources
The following section lists helpful reference applications, articles, guides and other
resources that demonstrate the use of env-schema in different use-cases and scenarios:
Acknowledgements
Kindly sponsored by Mia Platform and
NearForm.
License
MIT