Home

Integrating With Supabase Auth

Supabase Edge Functions and Auth.

Edge Functions work seamlessly with Supabase Auth.

Auth Context#

When a user makes a request to an Edge Function, you can use the Authorization header to set the Auth context in the Supabase client:


_12
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
_12
_12
Deno.serve(async (req: Request) => {
_12
_12
const authHeader = req.headers.get('Authorization')!
_12
const supabaseClient = createClient(
_12
Deno.env.get('SUPABASE_URL') ?? '',
_12
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
_12
{ global: { headers: { Authorization: authHeader } } }
_12
)
_12
_12
})

Importantly, this is done inside the Deno.serve() callback argument, so that the Authorization header is set for each request.

Fetching the user#

After initializing a Supabase client with the Auth context, you can use getUser() to fetch the user object, and run queries in the context of the user with Row Level Security (RLS) policies enforced.


_20
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
_20
_20
Deno.serve(async (req: Request) => {
_20
_20
const supabaseClient = createClient(
_20
Deno.env.get('SUPABASE_URL') ?? '',
_20
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
_20
{ global: { headers: { Authorization: req.headers.get('Authorization')! } } }
_20
)
_20
_20
// Get the session or user object
_20
const { data } = await supabaseClient.auth.getUser()
_20
const user = data.user
_20
_20
return new Response(JSON.stringify({ user }), {
_20
headers: { 'Content-Type': 'application/json' },
_20
status: 200,
_20
})
_20
_20
})

Row Level Security#

After initializing a Supabase client with the Auth context, all queries will be executed with the context of the user. For database queries, this means Row Level Security will be enforced.


_19
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
_19
_19
Deno.serve(async (req: Request) => {
_19
_19
const supabaseClient = createClient(
_19
Deno.env.get('SUPABASE_URL') ?? '',
_19
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
_19
{ global: { headers: { Authorization: req.headers.get('Authorization')! } } }
_19
)
_19
_19
// Database queries will have RLS policies enforced
_19
const { data, error } = await supabaseClient.from('profiles').select('*')
_19
_19
return new Response(JSON.stringify({ data }), {
_19
headers: { 'Content-Type': 'application/json' },
_19
status: 200,
_19
})
_19
_19
})

Example code#

See a full example on GitHub.