Edge Functions

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:


_15
import { createClient } from 'jsr:@supabase/supabase-js@2'
_15
_15
Deno.serve(async (req: Request) => {
_15
_15
const supabaseClient = createClient(
_15
Deno.env.get('SUPABASE_URL') ?? '',
_15
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
_15
);
_15
_15
// Get the session or user object
_15
const authHeader = req.headers.get('Authorization')!;
_15
const token = authHeader.replace('Bearer ', '');
_15
const { data } = await supabaseClient.auth.getUser(token);
_15
_15
})

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.


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

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.


_21
import { createClient } from 'jsr:@supabase/supabase-js@2'
_21
_21
Deno.serve(async (req: Request) => {
_21
_21
const supabaseClient = createClient(
_21
Deno.env.get('SUPABASE_URL') ?? '',
_21
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
_21
);
_21
_21
// Get the session or user object
_21
const authHeader = req.headers.get('Authorization')!;
_21
const token = authHeader.replace('Bearer ', '');
_21
const { data: userData } = await supabaseClient.auth.getUser(token);
_21
const { data, error } = await supabaseClient.from('profiles').select('*');
_21
_21
return new Response(JSON.stringify({ data }), {
_21
headers: { 'Content-Type': 'application/json' },
_21
status: 200,
_21
})
_21
_21
})

Example code

See a full example on GitHub.