Home

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.


_10
cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.env

Code#

Make sure you have the latest version of the Supabase CLI installed.

Create a new function in your project:


_10
supabase functions new upstash-redis-counter

And add the code to the index.ts file:

index.ts

_35
import { serve } from 'https://deno.land/std@0.177.0/http/server.ts'
_35
import { Redis } from 'https://deno.land/x/upstash_redis@v1.19.3/mod.ts'
_35
_35
console.log(`Function "upstash-redis-counter" up and running!`)
_35
_35
serve(async (_req) => {
_35
try {
_35
const redis = new Redis({
_35
url: Deno.env.get('UPSTASH_REDIS_REST_URL')!,
_35
token: Deno.env.get('UPSTASH_REDIS_REST_TOKEN')!,
_35
})
_35
_35
const deno_region = Deno.env.get('DENO_REGION')
_35
if (deno_region) {
_35
// Increment region counter
_35
await redis.hincrby('supa-edge-counter', deno_region, 1)
_35
} else {
_35
// Increment localhost counter
_35
await redis.hincrby('supa-edge-counter', 'localhost', 1)
_35
}
_35
_35
// Get all values
_35
const counterHash: Record<string, number> | null = await redis.hgetall('supa-edge-counter')
_35
const counters = Object.entries(counterHash!)
_35
.sort(([, a], [, b]) => b - a) // sort desc
_35
.reduce((r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v } }), {
_35
total: 0,
_35
regions: {},
_35
})
_35
_35
return new Response(JSON.stringify({ counters }), { status: 200 })
_35
} catch (error) {
_35
return new Response(JSON.stringify({ error: error.message }), { status: 200 })
_35
}
_35
})

Run locally#


_10
supabase start
_10
supabase functions serve --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env

Navigate to http://localhost:54321/functions/v1/upstash-redis-counter.

Deploy#


_10
supabase functions deploy upstash-redis-counter --no-verify-jwt
_10
supabase secrets set --env-file supabase/functions/upstash-redis-counter/.env