Edge Functions

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

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

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