@fastify/env
TypeScript icon, indicating that this package has built-in type declarations

4.3.0 • Public • Published

@fastify/env

CI NPM version js-standard-style

Fastify plugin to check environment variables

Install

npm i @fastify/env

Usage

const fastify = require('fastify')()
const fastifyEnv = require('@fastify/env')

const schema = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'string',
      default: 3000
    }
  }
}

const options = {
  confKey: 'config', // optional, default: 'config'
  schema: schema,
  data: data // optional, default: process.env
}

fastify
  .register(fastifyEnv, options)
  .ready((err) => {
    if (err) console.error(err)

    console.log(fastify.config) // or fastify[options.confKey]
    // output: { PORT: 3000 }
  })

This module is a wrapper around env-schema. To read an .env file you must set dotenv in the options:

const options = {
  dotenv: true // will read .env in root folder
}

// or, pass config options avalible on dotenv module
const options = {
  dotenv: {
    path: `${__dirname}/.env`,
    debug: true
  }
}

Using @fastify/env to configure other plugins

The @fastify/env plugin loads asynchronously. If you wish to use its values in a different plugin before the boot sequence, you need to make sure that:

  1. @fastify/env is registered first.
  2. Await the plugin registration or await after()
await fastify.register(fastifyEnv)
// fastify.config can be used in here

OR

fastify.register(fastifyEnv)
await fastify
// fastify.config can be used in here

NB Support for additional properties in the schema is disabled for this plugin, with the additionalProperties flag set to false internally.

Typescript

In order to have typing for the fastify instance, you should follow the example below:

declare module 'fastify' {
  interface FastifyInstance {
    config: { // this should be same as the confKey in options
      // specify your typing here
    };
  }
}

Acknowledgements

Kindly sponsored by Mia Platform

Readme

Keywords

Package Sidebar

Install

npm i @fastify/env

Weekly Downloads

34,252

Version

4.3.0

License

MIT

Unpacked Size

13.4 kB

Total Files

13

Last publish

Collaborators

  • gurgunday
  • metcoder95
  • galvez
  • simenb
  • coopflow
  • simoneb
  • rafaelgss
  • starptech
  • delvedor
  • matteo.collina
  • allevo
  • jsumners
  • zekth
  • eomm
  • fox1t
  • airhorns
  • kibertoad
  • climba03003
  • is2ei
  • fdawgs