Have ideas to improve npm?Join in the discussion! »

    env-schema
    TypeScript icon, indicating that this package has built-in type declarations

    3.0.1 • Public • Published

    env-schema

    CI workflow NPM version Known Vulnerabilities Coverage Status js-standard-style

    Utility to check environment variables using JSON schema, Ajv and dotenv.

    Install

    npm install --save env-schema
    

    Usage

    const envSchema = require('env-schema')
    
    const schema = {
      type: 'object',
      required: [ 'PORT' ],
      properties: {
        PORT: {
          type: 'string',
          default: 3000
        }
      }
    }
    
    const config = envSchema({
      schema: schema,
      data: data // optional, default: process.env
      dotenv: true // load .env if it's there, default: false
    })
    
    console.log(config)
    // output: { PORT: 3000 }

    It is possible to also use fluent-json-schema:

    const envSchema = require('env-schema')
    const S = require('fluent-json-schema')
    
    const config = envSchema({
      schema: S.object().prop('port', S.string().default('3000').required()),
      data: data, // optional, default: process.env
      dotenv: true, // load .env if it's 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.

    Custom keywords

    This library supports the following Ajv custom keywords:

    separator

    Type: string

    Applies to type: string

    When present, the value provided will be split based by 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's there, default: false
    }) 
    
    // config.data => ['127.0.0.1', '0.0.0.0']

    Acknowledgements

    Kindly sponsored by Mia Platform and NearForm.

    License

    MIT

    Install

    npm i env-schema

    DownloadsWeekly Downloads

    14,069

    Version

    3.0.1

    License

    MIT

    Unpacked Size

    20.5 kB

    Total Files

    13

    Last publish

    Collaborators

    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar
    • avatar