### Install @fastify/redis Source: https://github.com/fastify/fastify-redis/blob/main/README.md Install the plugin using npm. Ensure compatibility with your Fastify version. ```bash npm i @fastify/redis ``` -------------------------------- ### Register Fastify Redis with Redis URL Source: https://context7.com/fastify/fastify-redis/llms.txt Register the plugin using a Redis connection string. Additional ioredis options can be passed alongside the URL. Ensure to await fastify.listen() for the server to start. ```javascript 'use strict' const Fastify = require('fastify') const fastifyRedis = require('@fastify/redis') const fastify = Fastify() fastify.register(fastifyRedis, { url: 'redis://:password@127.0.0.1:6379/0', connectTimeout: 5000, maxRetriesPerRequest: 3 }) fastify.get('/session/:id', async (req, reply) => { const session = await fastify.redis.hgetall(`session:${req.params.id}`) if (!session || Object.keys(session).length === 0) { return reply.code(404).send({ error: 'Session not found' }) } return session }) await fastify.listen({ port: 3000 }) ``` -------------------------------- ### Access and Use Redis Client in Fastify Source: https://github.com/fastify/fastify-redis/blob/main/README.md Access the Redis client via `fastify.redis` after registration. The client is automatically closed when the Fastify instance closes. This example shows GET and SET operations. ```javascript '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}`) }) ``` -------------------------------- ### Interact with Redis Streams Source: https://github.com/fastify/fastify-redis/blob/main/README.md Utilize Redis streams for message queuing and event sourcing. Requires Redis 5.0 or greater. The example demonstrates adding and reading from a stream. ```javascript '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) } }) ``` -------------------------------- ### Using Redis Streams with Fastify Redis Source: https://context7.com/fastify/fastify-redis/llms.txt Leverage the full ioredis API for Redis Streams commands (e.g., XADD, XREAD) introduced in Redis 5.0. This example demonstrates adding orders to a stream and reading them. ```javascript 'use strict' const Fastify = require('fastify') const fastifyRedis = require('@fastify/redis') const fastify = Fastify() fastify.register(fastifyRedis, { host: '127.0.0.1', port: 6379 }) const STREAM = 'events:orders' fastify.post('/orders', async (req, reply) => { const { orderId, product, quantity } = req.body // Append an event to the stream; '*' lets Redis auto-generate the entry ID const entryId = await fastify.redis.xadd( STREAM, '*', 'orderId', orderId, 'product', product, 'quantity', String(quantity) ) return { entryId } // e.g. { entryId: "1700000000000-0" } }) fastify.get('/orders', async (req, reply) => { const since = req.query.since || '0' // '0' reads from the beginning // Returns: [[streamName, [[entryId, [field, val, field, val]], ...]]] const results = await fastify.redis.xread('COUNT', 100, 'STREAMS', STREAM, since) if (!results) return [] const entries = results[0][1] return entries.map(([id, fields]) => { const obj = { id } for (let i = 0; i < fields.length; i += 2) { obj[fields[i]] = fields[i + 1] } return obj }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Handling Redis Connection Errors During Registration Source: https://context7.com/fastify/fastify-redis/llms.txt The plugin validates the Redis connection during registration before the server starts. Configure `pluginTimeout` for the Fastify instance to control how long the plugin waits for a connection. Failed connections can result in `ERR_AVVIO_PLUGIN_TIMEOUT` or specific errors related to host or TLS configuration. ```javascript 'use strict' const Fastify = require('fastify') const fastifyRedis = require('@fastify/redis') const fastify = Fastify({ pluginTimeout: 10000 }) fastify.register(fastifyRedis, { host: 'my-redis-host.example.com', port: 6379, tls: { rejectUnauthorized: true // SELF_SIGNED_CERT_IN_CHAIN will surface as a startup error } }) fastify.ready().then(() => { console.log('Redis connected successfully') }).catch(err => { // Possible errors: // - ERR_AVVIO_PLUGIN_TIMEOUT (host unreachable, reconnection exhausted) // - ReplyError (AUTH failed, wrong password) // - Error: SELF_SIGNED_CERT_IN_CHAIN console.error('Failed to connect to Redis:', err.message) process.exit(1) }) ``` -------------------------------- ### Create New Redis Client with Options Source: https://github.com/fastify/fastify-redis/blob/main/README.md Register the plugin with Fastify, providing detailed connection options like host, password, port, and IP family. ```javascript fastify.register(require('@fastify/redis'), { host: '127.0.0.1', password: '***', port: 6379, // Redis port family: 4 // 4 (IPv4) or 6 (IPv6) }) ``` -------------------------------- ### Create New Redis Client by Host Source: https://github.com/fastify/fastify-redis/blob/main/README.md Register the plugin with Fastify, specifying the Redis host. Options passed here are forwarded to the ioredis client. ```javascript fastify.register(require('@fastify/redis'), { host: '127.0.0.1' }) ``` -------------------------------- ### Create New Redis Client by URL Source: https://github.com/fastify/fastify-redis/blob/main/README.md Register the plugin with Fastify, specifying the Redis connection URL. Additional Redis options can be included. ```javascript fastify.register(require('@fastify/redis'), { url: 'redis://127.0.0.1', /* other redis options */ }) ``` -------------------------------- ### Use Existing Redis Client Instance Source: https://github.com/fastify/fastify-redis/blob/main/README.md Register the plugin with an existing ioredis client instance. The client is not automatically closed by default. ```javascript 'use strict' const fastify = require('fastify')() const Redis = require('ioredis') const client = new Redis({ host: 'localhost', port: 6379 }) fastify.register(require('@fastify/redis'), { client }) ``` -------------------------------- ### Register Multiple Redis Instances with Namespaces Source: https://github.com/fastify/fastify-redis/blob/main/README.md Use the 'namespace' option to register distinct Redis client instances. Access them via `fastify.redis.`. ```javascript '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) } }) ``` -------------------------------- ### Use Existing Redis Cluster Instance Source: https://github.com/fastify/fastify-redis/blob/main/README.md Register the plugin with an existing ioredis Cluster instance. The client is not automatically closed by default. ```javascript '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 }) ``` -------------------------------- ### Register Fastify Redis with Host and Port Source: https://context7.com/fastify/fastify-redis/llms.txt Register the plugin to connect to a Redis server using host and port. The fastify.redis decorator is available after fastify.ready(). Connection is closed on fastify.close(). ```javascript 'use strict' const Fastify = require('fastify') const fastifyRedis = require('@fastify/redis') const fastify = Fastify({ logger: true }) fastify.register(fastifyRedis, { host: '127.0.0.1', port: 6379, password: 'your-strong-password', family: 4 // 4 = IPv4, 6 = IPv6 }) fastify.get('/cache/:key', async (req, reply) => { const value = await fastify.redis.get(req.params.key) if (!value) { return reply.code(404).send({ error: 'Key not found' }) } return { key: req.params.key, value } }) fastify.post('/cache', async (req, reply) => { const { key, value, ttl } = req.body if (ttl) { await fastify.redis.set(key, value, 'EX', ttl) } else { await fastify.redis.set(key, value) } return { status: 'ok' } }) fastify.listen({ port: 3000 }, err => { if (err) throw err // fastify.redis is now a live ioredis client }) ``` -------------------------------- ### Register Fastify Redis with Existing ioredis Client Source: https://context7.com/fastify/fastify-redis/llms.txt Inject a pre-existing ioredis client (standalone or cluster). Set 'closeClient: true' to enable automatic closing of the client on Fastify shutdown. Supports namespaces for multiple clients. ```javascript 'use strict' const Fastify = require('fastify') const Redis = require('ioredis') const fastifyRedis = require('@fastify/redis') const fastify = Fastify() // Pre-existing standalone client const redisClient = new Redis({ host: 'localhost', port: 6379 }) fastify.register(fastifyRedis, { client: redisClient, closeClient: true // quit() is called when fastify.close() is called }) // Pre-existing cluster client const Redis2 = require('ioredis') const clusterClient = new Redis2.Cluster([ { host: '127.0.0.1', port: 7000 }, { host: '127.0.0.1', port: 7001 } ]) // Register cluster under a namespace fastify.register(fastifyRedis, { client: clusterClient, namespace: 'cluster', closeClient: true }) await fastify.ready() // fastify.redis → standalone client // fastify.redis.cluster → cluster client await fastify.redis.set('hello', 'world') await fastify.redis.cluster.set('distributed-key', 'value') await fastify.close() ``` -------------------------------- ### Registering Multiple Namespaced Redis Instances Source: https://context7.com/fastify/fastify-redis/llms.txt Use the `namespace` option to register multiple independent Redis clients within the same Fastify instance. Each namespace is accessible via `fastify.redis[namespace]`. Attempting to register duplicate namespaces will result in an error. ```javascript 'use strict' const Fastify = require('fastify') const fastifyRedis = require('@fastify/redis') const fastify = Fastify() fastify .register(fastifyRedis, { host: '127.0.0.1', port: 6379, namespace: 'cache' }) .register(fastifyRedis, { host: '127.0.0.1', port: 6380, namespace: 'sessions' }) fastify.get('/user/:id', async (req, reply) => { const { id } = req.params // Read from the cache namespace const cached = await fastify.redis.cache.get(`user:${id}`) if (cached) return JSON.parse(cached) // Simulate a DB lookup, then store in cache with a TTL const user = { id, name: 'Alice', role: 'admin' } await fastify.redis.cache.set(`user:${id}`, JSON.stringify(user), 'EX', 300) // Update session activity in the sessions namespace await fastify.redis.sessions.hset(`session:${id}`, 'lastSeen', Date.now()) return user }) // Registering the same namespace twice throws: // Error: Redis 'cache' instance namespace has already been registered fastify.listen({ port: 3000 }) ``` -------------------------------- ### Automatically Close Existing Redis Client Source: https://github.com/fastify/fastify-redis/blob/main/README.md Register the plugin with an existing Redis client and set `closeClient` to `true` to enable automatic client connection closing when the Fastify server shuts down. ```javascript fastify.register(require('@fastify/redis'), { client, closeClient: true }) ``` -------------------------------- ### TypeScript Usage with Fastify Redis Source: https://context7.com/fastify/fastify-redis/llms.txt The plugin provides TypeScript declarations that augment `FastifyInstance` with the `redis` property, enabling type-safe access to Redis clients, including namespaced instances. ```typescript import Fastify from 'fastify' import fastifyRedis from '@fastify/redis' const fastify = Fastify() fastify.register(fastifyRedis, { host: '127.0.0.1', port: 6379 }) // Or with namespace fastify.register(fastifyRedis, { url: 'redis://127.0.0.1', namespace: 'sessions' }) fastify.get('/ping', async (_req, reply) => { // fastify.redis is typed as FastifyRedis (ioredis Redis & namespaced index) const pong = await fastify.redis.ping() const sessionPong = await fastify.redis.sessions.ping() return { pong, sessionPong } }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Customizing Redis Client Info Tag Source: https://context7.com/fastify/fastify-redis/llms.txt Configure the `clientInfoTag` option to set a custom tag sent to Redis via `CLIENT SETINFO`. This is useful for identifying your application in Redis monitoring tools. The default tag is `fastify-redis_v{version}`. ```javascript 'use strict' const Fastify = require('fastify') const fastifyRedis = require('@fastify/redis') const fastify = Fastify() fastify.register(fastifyRedis, { host: '127.0.0.1', port: 6379, clientInfoTag: 'my-app-v2.3.0' // Redis CLIENT INFO will show: lib-name=ioredis(my-app-v2.3.0) }) await fastify.ready() await fastify.close() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.