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.

1
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:

1
supabase functions new upstash-redis-counter

And add the code to the index.ts file:

1
import { Redis } from 'https://deno.land/x/upstash_redis@v1.19.3/mod.ts'
2
3
console.log(`Function "upstash-redis-counter" up and running!`)
4
5
Deno.serve(async (_req) => {
6
try {
7
const redis = new Redis({
8
url: Deno.env.get('UPSTASH_REDIS_REST_URL')!,
9
token: Deno.env.get('UPSTASH_REDIS_REST_TOKEN')!,
10
})
11
12
const deno_region = Deno.env.get('DENO_REGION')
13
if (deno_region) {
14
// Increment region counter
15
await redis.hincrby('supa-edge-counter', deno_region, 1)
16
} else {
17
// Increment localhost counter
18
await redis.hincrby('supa-edge-counter', 'localhost', 1)
19
}
20
21
// Get all values
22
const counterHash: Record<string, number> | null = await redis.hgetall('supa-edge-counter')
23
const counters = Object.entries(counterHash!)
24
.sort(([, a], [, b]) => b - a) // sort desc
25
.reduce((r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v } }), {
26
total: 0,
27
regions: {},
28
})
29
30
return new Response(JSON.stringify({ counters }), { status: 200 })
31
} catch (error) {
32
return new Response(JSON.stringify({ error: error.message }), { status: 200 })
33
}
34
})

Run locally

1
supabase start
2
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

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