Install @fastify/redis
mainInstall the plugin using npm:
npm i @fastify/redisrepository·main·Indexed 42 days ago
https://github.com/fastify/fastify-redisA Fastify plugin that provides a shared Redis connection across the server, powered by the ioredis client. Version 9.0.0 supports standard ioredis instances, Redis Cluster, and Redis streams (for Redis server v5.0+). It allows for multiple independent connections via namespaces and provides access to the client through fastify.redis.
Install the plugin using npm:
npm i @fastify/redisWhile ioredis handles most errors silently, @fastify/redis performs a connection check during plugin registration. If the connection cannot be established within the expected timeframe, you may encounter:
ERR_AVVIO_PLUGIN_TIMEOUT: The connection attempt timed out.If your Redis server is version 5.0 or greater, @fastify/redis supports Redis streams. You can use standard stream commands like xadd and xread directly on the fastify.redis instance.
fastify.get('/streams', async (request, reply) => {
// Write an event to the stream
await fastify.redis.xadd(['my awesome fastify stream name', '*', 'hello', 'fastify is awesome'])
// Read events from the beginning of the stream
let redisStream = await fastify.redis.xread(['STREAMS', 'my awesome fastify stream name', 0])
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()}`)
for (const key in e[1]) {
response.push(e[1][key].toString())
}
}
return { output: response }
})Once registered, the Redis client is available on the Fastify instance as fastify.redis. By default, 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,
family: 4
})
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}`)
})Use the namespace option to register multiple independent Redis connections. Each connection will be accessible via fastify.redis[namespace].
const fastify = require('fastify')()
fastify
.register(require('@fastify/redis'), {
host: '127.0.0.1',
port: 6380,
namespace: 'hello'
})
.register(require('@fastify/redis'), {
client: redisInstance,
namespace: 'world'
})
// Accessing the 'hello' instance
fastify.get('/hello', (req, reply) => {
const { redis } = fastify
redis.hello.get(req.query.key, (err, val) => {
reply.send(err || val)
})
})
// Accessing the 'world' instance
fastify.get('/world', (req, reply) => {
const { redis } = fastify
redis['world'].get(req.query.key, (err, val) => {
reply.send(err || val)
})
})Register the plugin with fastify.register. The options object passed to register is passed directly to the underlying ioredis client. You can specify connection details via host and port, or via a single url string.
Supported options include:
host: Redis server hostnameport: Redis portpassword: Redis passwordurl: Redis connection URLfamily: IP version (4 for IPv4, 6 for IPv6)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' })
// OR with more options
fastify.register(require('@fastify/redis'), {
host: '127.0.0.1',
password: '***',
port: 6379,
family: 4
})You can provide your own ioredis instance by passing it in the client option.
Important Lifecycle Note: When providing an existing client, @fastify/redis will not automatically close the connection when the Fastify server shuts down. To enable automatic closing, set closeClient: true in the registration options.
Supported client types:
ioredis instanceioredis.Cluster instanceconst fastify = require('fastify')()
const Redis = require('ioredis')
// Using a standard client
const client = new Redis({ host: 'localhost', port: 6379 })
fastify.register(require('@fastify/redis'), { client })
// OR using a Cluster client
const cluster = new Redis.Cluster([{ host: 'localhost', port: 6379 }])
fastify.register(require('@fastify/redis'), { client: cluster })
// OR to ensure the client closes on shutdown
fastify.register(require('@fastify/redis'), { client, closeClient: true })When registering the plugin, you can pass the following options:
| Option | Type | Description |
|---|---|---|
url | string | The Redis connection URL (e.g., redis://localhost:6379). |
namespace | string | If provided, the Redis client is attached to fastify.redis[namespace] instead of fastify.redis. |
client | ioredis instance | An existing ioredis client instance to use. |
closeClient | boolean | If true, the plugin will call .quit() on the client when the Fastify instance closes. Defaults to false if a custom client is provided, but is managed automatically for new clients. |
clientInfoTag | string | A custom tag for identifying the framework in Redis CLIENT SETINFO. If not provided, it defaults to fastify-redis_v<version> |
...redisOptions | object | Any additional options supported by ioredis. |
Ensure your plugin and Fastify versions are compatible based on the following table:
| Plugin version | Fastify 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 |
To manage multiple Redis connections, use the namespace option. This decorates fastify.redis as a container object where each key is a namespace containing its respective client.
Note: If you use namespaces, you cannot use the default fastify.redis decoration for a single client; all clients will reside under fastify.redis[namespace].
const Fastify = require('fastify')
const fastifyRedis = require('@fastify/redis')
const fastify = Fastify()
// Register first instance
fastify.register(fastifyRedis, {
namespace: 'cache',
url: 'redis://localhost:6379'
})
// Register second instance
fastify.register(fastifyRedis, {
namespace: 'sessions',
url: 'redis://localhost:6380'
})
fastify.ready().then(() => {
// Access via namespaces
fastify.redis.cache.get('key')
fastify.redis.sessions.get('session_id')
})Register @fastify/redis to add a Redis client to your Fastify instance. You can either use a connection URL, provide an existing ioredis client instance, or pass ioredis configuration options.
If you provide a namespace in the options, the plugin will decorate fastify.redis as an object containing multiple named instances instead of decorating fastify.redis directly with a single client. This allows you to register multiple Redis connections.
const Fastify = require('fastify')
const fastifyRedis = require('@fastify/redis')
const fastify = Fastify()
fastify.register(fastifyRedis, {
url: 'redis://127.0.0.1:6379'
})
fastify.ready()
.then(() => {
// Access the client via fastify.redis
fastify.redis.get('key', (err, val) => {
console.log(val)
})
})