All files / lib/redis client.ts

85.71% Statements 18/21
40% Branches 2/5
100% Functions 2/2
85.71% Lines 18/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 471x                           1x           1x 15x   15x 15x 15x 15x 15x 15x 15x 15x   15x 15x 15x                 1x 2x 2x  
/**
 * Upstash Redis Client
 *
 * Serverless Redis client for rate limiting and caching.
 * Vercel auto-injects env vars when connected via Storage integration.
 *
 * Supports all naming conventions:
 * - Vercel Storage: KV_REST_API_URL / KV_REST_API_TOKEN
 * - Vercel KV (Upstash): UPSTASH_REDIS_KV_REST_API_URL / UPSTASH_REDIS_KV_REST_API_TOKEN
 * - Upstash direct: UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN
 */
 
import { Redis } from '@upstash/redis';
 
let redis: Redis | null = null;
 
/**
 * Get the Upstash Redis client (singleton).
 * Returns null if env vars are not configured.
 */
export function getRedisClient(): Redis | null {
  if (redis) return redis;
 
  const url =
    process.env.KV_REST_API_URL ||
    process.env.UPSTASH_REDIS_KV_REST_API_URL ||
    process.env.UPSTASH_REDIS_REST_URL;
  const token =
    process.env.KV_REST_API_TOKEN ||
    process.env.UPSTASH_REDIS_KV_REST_API_TOKEN ||
    process.env.UPSTASH_REDIS_REST_TOKEN;
 
  if (!url || !token) {
    return null;
  }
 
  redis = new Redis({ url, token });
  return redis;
}
 
/**
 * Check if Redis is available
 */
export function isRedisAvailable(): boolean {
  return getRedisClient() !== null;
}