![Maven Central Adds Sigstore Signature Validation](https://cdn.sanity.io/images/cgdhsj6q/production/7da3bc8a946cfb5df15d7fcf49767faedc72b483-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Maven Central Adds Sigstore Signature Validation
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
env-schema
Advanced tools
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.
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);
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 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 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.
Utility to check environment variables using JSON schema, Ajv, and dotenv.
npm install --save env-schema
const envSchema = require('env-schema')
const schema = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema({
schema: schema,
data: data, // optional, default: process.env
dotenv: true // load .env if it is there, default: false
// or you can pass DotenvConfigOptions
// dotenv: {
// path: '/custom/path/to/.env'
// }
})
console.log(config)
// output: { PORT: 3000 }
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)
// output: { PORT: 3000 }
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.
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, // optional, default: process.env
dotenv: true, // load .env if it is there, default: false
expandEnv: true, // use dotenv-expand, default: false
})
console.log(config)
// output: { PORT: 3000 }
NB Support for additional properties in the schema is disabled for this plugin, with the additionalProperties
flag set to false
internally.
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, // optional, default: process.env
dotenv: true // load .env if it is there, default: false
})
// config.data => ['127.0.0.1', '0.0.0.0']
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)
// output: { names: ['foo', 'bar'] }
You can specify the type of your config
:
import envSchema from 'env-schema';
interface Env {
PORT: number;
}
const schema = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema<Env>({
schema,
})
If no type is specified the config
will have the EnvSchemaData
type.
export type EnvSchemaData = {
[key: string]: unknown;
}
Kindly sponsored by Mia Platform and NearForm.
MIT
FAQs
Validate your env variables using Ajv and dotenv
The npm package env-schema receives a total of 90,391 weekly downloads. As such, env-schema popularity was classified as popular.
We found that env-schema demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.