@fastify/redis

repository·main·Indexed 42 days ago

https://github.com/fastify/fastify-redis

A 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.

Tokens
2.8K
Snippets
8
Records
11
Agent score
3%

What's inside fastify-redis

  1. Troubleshoot Redis connection errors

    main

    While 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.
    • A dedicated error for an invalid connection.
  2. Use Redis Streams

    main

    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 }
    })
  3. Access the Redis Client via fastify.redis

    main

    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}`)
    })
  4. Register multiple Redis client instances using namespaces

    main

    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)
      })
    })
  5. Create a new Redis Client

    main

    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 hostname
    • port: Redis port
    • password: Redis password
    • url: Redis connection URL
    • family: 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
    })
  6. Use an existing Redis or Redis Cluster client

    main

    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:

    • Standard ioredis instance
    • ioredis.Cluster instance
    const 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 })
  7. Configure @fastify/redis options

    main

    When registering the plugin, you can pass the following options:

    OptionTypeDescription
    urlstringThe Redis connection URL (e.g., redis://localhost:6379).
    namespacestringIf provided, the Redis client is attached to fastify.redis[namespace] instead of fastify.redis.
    clientioredis instanceAn existing ioredis client instance to use.
    closeClientbooleanIf 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.
    clientInfoTagstringA custom tag for identifying the framework in Redis CLIENT SETINFO. If not provided, it defaults to fastify-redis_v<version>
    ...redisOptionsobjectAny additional options supported by ioredis.
  8. Register multiple Redis instances using namespaces

    main

    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')
    })
  9. Register the @fastify/redis plugin

    main

    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)
        })
      })