Upstash Redis
A Redis counter example that stores a hash of function invocation count per region. Find the code on GitHub.
Redis database setup#
Create a Redis database using the Upstash Console or Upstash CLI.
Select the Global type to minimize the latency from all edge locations. Copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN to your .env file.
You'll find them under Details > REST API > .env.
1cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.envCode#
Make sure you have the latest version of the Supabase CLI installed.
Create a new function in your project:
1supabase functions new upstash-redis-counterAnd add the code to the index.ts file:
1import { Redis } from 'https://deno.land/x/upstash_redis@v1.19.3/mod.ts'2import { withSupabase } from 'npm:@supabase/server@^1'34console.log(`Function "upstash-redis-counter" up and running!`)56// Open endpoint for testing. In production, implement an authorization layer in the handler or switch the auth mode.7export default {8 fetch: withSupabase({ auth: 'none' }, async (req, ctx) => {9 try {10 const redis = new Redis({11 url: Deno.env.get('UPSTASH_REDIS_REST_URL')!,12 token: Deno.env.get('UPSTASH_REDIS_REST_TOKEN')!,13 })1415 const deno_region = Deno.env.get('DENO_REGION')16 if (deno_region) {17 // Increment region counter18 await redis.hincrby('supa-edge-counter', deno_region, 1)19 } else {20 // Increment localhost counter21 await redis.hincrby('supa-edge-counter', 'localhost', 1)22 }2324 // Get all values25 const counterHash: Record<string, number> | null = await redis.hgetall('supa-edge-counter')26 const counters = Object.entries(counterHash!)27 .sort(([, a], [, b]) => b - a) // sort desc28 .reduce((r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v } }), {29 total: 0,30 regions: {},31 })3233 return Response.json({ counters })34 } catch (error) {35 return Response.json({ error: error.message }, { status: 500 })36 }37 }),38}Run locally#
1supabase start2supabase functions serve --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.envNavigate to http://localhost:54321/functions/v1/upstash-redis-counter.
Deploy#
1supabase functions deploy upstash-redis-counter --no-verify-jwt2supabase secrets set --env-file supabase/functions/upstash-redis-counter/.env