Edge Functions

Integrating with Supabase Storage


Edge Functions work seamlessly with Supabase Storage. This allows you to:

  • Upload generated content directly from your functions
  • Implement cache-first patterns for better performance
  • Serve files with built-in CDN capabilities

Basic file operations

Use the Supabase client to upload files directly from your Edge Functions. You'll need the service role key for server-side storage operations:

1
import { createClient } from 'npm:@supabase/supabase-js@2'
2
3
Deno.serve(async (req) => {
4
const supabaseAdmin = createClient(
5
Deno.env.get('SUPABASE_URL') ?? '',
6
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
7
)
8
9
// Generate your content
10
const fileContent = await generateImage()
11
12
// Upload to storage
13
const { data, error } = await supabaseAdmin.storage
14
.from('images')
15
.upload(`generated/${filename}.png`, fileContent.body!, {
16
contentType: 'image/png',
17
cacheControl: '3600',
18
upsert: false,
19
})
20
21
if (error) {
22
throw error
23
}
24
25
return new Response(JSON.stringify({ path: data.path }))
26
})

Cache-first pattern

Check storage before generating new content to improve performance:

1
const STORAGE_URL = 'https://your-project.supabase.co/storage/v1/object/public/images'
2
3
Deno.serve(async (req) => {
4
const url = new URL(req.url)
5
const username = url.searchParams.get('username')
6
7
try {
8
// Try to get existing file from storage first
9
const storageResponse = await fetch(`${STORAGE_URL}/avatars/${username}.png`)
10
11
if (storageResponse.ok) {
12
// File exists in storage, return it directly
13
return storageResponse
14
}
15
16
// File doesn't exist, generate it
17
const generatedImage = await generateAvatar(username)
18
19
// Upload to storage for future requests
20
const { error } = await supabaseAdmin.storage
21
.from('images')
22
.upload(`avatars/${username}.png`, generatedImage.body!, {
23
contentType: 'image/png',
24
cacheControl: '86400', // Cache for 24 hours
25
})
26
27
if (error) {
28
console.error('Upload failed:', error)
29
}
30
31
return generatedImage
32
} catch (error) {
33
return new Response('Error processing request', { status: 500 })
34
}
35
})