@fastify/env

中文文档
7.0.1发布于 2026/10/09MITTypeScriptCommonJS构建来源已验证近 30 天下载 94万

Fastify plugin to check environment variables

原始使用文档
文档目录8 节
  1. Install
  2. Compatibility
  3. Usage
  4. Formats and custom Ajv options
  5. Using @fastify/env to configure other plugins
  6. Typescript
  7. Acknowledgments
  8. License

@fastify/env

CI NPM version neostandard javascript style

Fastify plugin to check environment variables

Install

npm i @fastify/env

Compatibility

Plugin versionFastify version
>=5.x^5.x
^4.x^4.x
>=2.x <4.x^3.x
>=0.x 2.x^2.x
>=0.x 2.x^1.x

Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.

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]
    console.log(fastify.getEnvs())
    // output: { PORT: 3000 }
  })

You can also use the function getEnvs() of the Request from within a handler function:

fastify.get('/', (request, reply) => {
    console.log(request.getEnvs())
    // output: { PORT: 3000 }
})

Note that the getEnvs decorators will not be added if they already exist.

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

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

// or, pass config options supported by env-schema
const options = {
  dotenv: {
    path: `${__dirname}/.env`,
    encoding: 'utf8'
  }
}

Formats and custom Ajv options

@fastify/env validates the schema with its own Ajv instance (provided by env-schema), independent from the one Fastify uses for routes. Formats or options configured on the Fastify instance (Fastify({ ajv: ... })), or coming from a type provider such as TypeBox, are not applied to the env schema, so using the format keyword results in:

unknown format "uuid" ignored in schema at path "#/properties/ID"

Register the formats on the plugin's Ajv instance with the ajv.customOptions option, which can be an Ajv options object or a function that receives the Ajv instance and returns it. For the standard formats you can use ajv-formats (npm i ajv-formats, it is not a dependency of this plugin):

await fastify.register(fastifyEnv, {
  schema: {
    type: 'object',
    required: ['ID'],
    properties: {
      ID: { type: 'string', format: 'uuid' }
    }
  },
  ajv: {
    customOptions (ajvInstance) {
      require('ajv-formats')(ajvInstance)
      // or: ajvInstance.addFormat('myFormat', (value) => /* ... */)
      return ajvInstance
    }
  }
})

With TypeBox (1.x, i.e. @fastify/type-provider-typebox >= 6) you can reuse the formats built into TypeBox:

import { Format, Type } from '@fastify/type-provider-typebox'

await fastify.register(fastifyEnv, {
  schema: Type.Object({
    ID: Type.String({ format: 'uuid' })
  }),
  ajv: {
    customOptions (ajvInstance) {
      for (const entry of Format.Entries()) {
        ajvInstance.addFormat(...entry)
      }
      // Or if you only want to register a specific format:
      // ajvInstance.addFormat('uuid', Format.Get('uuid'))
      return ajvInstance
    }
  }
})

See the env-schema documentation for all the supported Ajv options.

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

To have typings for the fastify instance, you should either:

  • use the declaration merging technique to enhance the FastifyInstance type with the property and its keys you have defined in the options:
declare module 'fastify' {
  interface FastifyInstance {
    config: { // this should be the same as the confKey in options
      // specify your typing here
      FOO: string
    };
  }
}

const fastify = Fastify()
fastify.register(fastifyEnv)

fastify.config.FOO // will be a string
fastify.config.BAR // error: Property BAR does not exist on type { FOO: string }
  • use the generic function getEnvs() to get the already typed object:
type Envs = {
  FOO: string
}

const fastify = Fastify()
await fastify.register(fastifyEnv)

const envs = fastify.getEnvs<Envs>() // envs will be of type Envs

envs.FOO // will be a string
envs.BAR // error: Property BAR does not exist on type Envs

If this is the case it is suggested to use json-schema-to-ts to have the type always synchronized with the actual schema.

Acknowledgments

Kindly sponsored by Mia Platform.

License

Licensed under MIT.

版本与发布记录

@fastify/env 共发布 15 个版本,首次发布于 2022/04/27;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
7.0.1latest2026/10/091 个月前
7.0.02026/06/095 个月前
6.0.02026/03/297 个月前
5.0.32025/09/281.1 年前
5.0.22025/01/051.9 年前
5.0.12024/09/212 年前

其他发布通道:next → 5.0.0。

关于 @fastify/env 的常见问题

@fastify/env 是什么?

Fastify plugin to check environment variables

如何安装 @fastify/env?

在项目目录运行 npm install @fastify/env,或使用 pnpm add / yarn add / bun add。

@fastify/env 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fastify/env 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@fastify/env 可以商用吗?

@fastify/env 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fastify/env 的下载量有多少?

根据 npm 官方下载统计,@fastify/env 在 2026/10/15 – 2026/11/13 这 30 天内被下载 940,305 次,日均约 31,344 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fastify/env 还在维护吗?

最新版本 7.0.1 发布于 2026/10/09(1 个月前);至今共发布 15 个版本,其中过去 12 个月发布了 3 个;首次发布于 2022/04/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。