@fastify/redis

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

Plugin to share a common Redis connection across Fastify.

原始使用文档
文档目录11 节
  1. Install
  2. Compatibility
  3. Usage
  4. Create a new Redis Client
  5. Accessing the Redis Client
  6. Using an existing Redis client
  7. Registering multiple Redis client instances
  8. Redis streams (Redis 5.0 or greater is required)
  9. Redis connection error
  10. Acknowledgments
  11. License

@fastify/redis

CI NPM version neostandard javascript style

Fastify Redis connection plugin; with this you can share the same Redis connection in every part of your server.

Install

npm i @fastify/redis

Compatibility

Plugin versionFastify version
>=7.x^5.x
^6.x^4.x
>=4.x <6.x^3.x
^3.x^2.x
>=1.x <3.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

Add it to your project with register and you are done!

Create a new Redis Client

Under the hood ioredis is used as client, the options that you pass to register will be passed to the Redis client.

const fastify = require('fastify')()

// create by specifying host
fastify.register(require('@fastify/redis'), { host: '127.0.0.1' })

// OR by specifying Redis URL
fastify.register(require('@fastify/redis'), { url: 'redis://127.0.0.1', /* other redis options */ })

// OR with more options
fastify.register(require('@fastify/redis'), {
  host: '127.0.0.1',
  password: '***',
  port: 6379, // Redis port
  family: 4   // 4 (IPv4) or 6 (IPv6)
})

Accessing the Redis Client

Once you have registered your plugin, you can access the Redis client via fastify.redis.

The client is automatically closed when the fastify instance is closed.

'use strict'

const Fastify = require('fastify')
const fastifyRedis = require('@fastify/redis')

const fastify = Fastify({ logger: true })

fastify.register(fastifyRedis, {
  host: '127.0.0.1',
  password: 'your strong password here',
  port: 6379, // Redis port
  family: 4   // 4 (IPv4) or 6 (IPv6)
})

fastify.get('/foo', (req, reply) => {
  const { redis } = fastify
  redis.get(req.query.key, (err, val) => {
    reply.send(err || val)
  })
})

fastify.post('/foo', (req, reply) => {
  const { redis } = fastify
  redis.set(req.body.key, req.body.value, (err) => {
    reply.send(err || { status: 'ok' })
  })
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})

Using an existing Redis client

You may also supply an existing Redis client instance by passing an options object with the client property set to the instance. In this case, the client is not automatically closed when the Fastify instance is closed.

'use strict'

const fastify = require('fastify')()
const Redis = require('ioredis')

const client = new Redis({ host: 'localhost', port: 6379 })

fastify.register(require('@fastify/redis'), { client })

You can also supply a Redis Cluster instance to the client:

'use strict'

const fastify = require('fastify')()
const Redis = require('ioredis')

const client = new Redis.Cluster([{ host: 'localhost', port: 6379 }]);

fastify.register(require('@fastify/redis'), { client })

Note: by default, @fastify/redis will not automatically close the client connection when the Fastify server shuts down.

To automatically close the client connection, set clientClose to true.

fastify.register(require('@fastify/redis'), { client, closeClient: true })

Registering multiple Redis client instances

By using the namespace option you can register multiple Redis client instances.

'use strict'

const fastify = require('fastify')()

fastify
  .register(require('@fastify/redis'), {
    host: '127.0.0.1',
    port: 6380,
    namespace: 'hello'
  })
  .register(require('@fastify/redis'), {
    client: redis,
    namespace: 'world'
  })

// Here we will use the `hello` named instance
fastify.get('/hello', (req, reply) => {
  const { redis } = fastify

  redis.hello.get(req.query.key, (err, val) => {
    reply.send(err || val)
  })
})

fastify.post('/hello', (req, reply) => {
  const { redis } = fastify

  redis['hello'].set(req.body.key, req.body.value, (err) => {
    reply.send(err || { status: 'ok' })
  })
})

// Here we will use the `world` named instance
fastify.get('/world', (req, reply) => {
  const { redis } = fastify

  redis['world'].get(req.query.key, (err, val) => {
    reply.send(err || val)
  })
})

fastify.post('/world', (req, reply) => {
  const { redis } = fastify

  redis.world.set(req.body.key, req.body.value, (err) => {
    reply.send(err || { status: 'ok' })
  })
})

fastify.listen({ port: 3000 }, function (err) {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

Redis streams (Redis 5.0 or greater is required)

@fastify/redis supports Redis streams out of the box.

'use strict'

const fastify = require('fastify')()

fastify.register(require('@fastify/redis'), {
  host: '127.0.0.1',
  port: 6380
})

fastify.get('/streams', async (request, reply) => {
  // We write an event to the stream 'my awesome fastify stream name', setting 'key' to 'value'
  await fastify.redis.xadd(['my awesome fastify stream name', '*', 'hello', 'fastify is awesome'])

  // We read events from the beginning of the stream called 'my awesome fastify stream name'
  let redisStream = await fastify.redis.xread(['STREAMS', 'my awesome fastify stream name', 0])

  // We parse the results
  let response = []
  let events = redisStream[0][1]

  for (let i = 0; i < events.length; i++) {
    const e = events[i]
    response.push(`#LOG: id is ${e[0].toString()}`)

    // We log each key
    for (const key in e[1]) {
      response.push(e[1][key].toString())
    }
  }

  reply.status(200)
  return { output: response }
  // Will return something like this :
  // { "output": ["#LOG: id is 1559985742035-0", "hello", "fastify is awesome"] }
})

fastify.listen({ port: 3000 }, function (err) {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

ℹ️ Note: you can find more information about Redis streams and the relevant commands here and here.

Redis connection error

The majority of errors are silent due to the ioredis silent error handling but during the plugin registration it will check that the connection with the redis instance is correctly estabilished. In this case, you can receive an ERR_AVVIO_PLUGIN_TIMEOUT error if the connection cannot be established in the expected time frame or a dedicated error for an invalid connection.

Acknowledgments

This project is kindly sponsored by:

Past sponsors:

  • LetzDoIt

License

Licensed under MIT.

版本与发布记录

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

版本发布日期距今
9.0.1latest2026/10/091 个月前
9.0.02026/08/142 个月前
8.0.02026/06/095 个月前
7.2.02026/01/319 个月前
7.1.02025/10/051.1 年前
7.0.22025/01/111.8 年前

其他发布通道:next → 7.0.0。

关于 @fastify/redis 的常见问题

@fastify/redis 是什么?

Plugin to share a common Redis connection across Fastify.

如何安装 @fastify/redis?

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

@fastify/redis 支持 TypeScript 吗?

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

@fastify/redis 支持 ESM 还是 CommonJS?

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

@fastify/redis 可以商用吗?

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

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

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

@fastify/redis 还在维护吗?

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