Auth

Edge Functions work seamlessly with Supabase Auth, allowing you to identify which user called your function.

When invoking a function with one of the client libraries, the logged in user's JWT is automatically attached to the function call and becomes accessible within your function.

This is important, for example, to identify which customer's credit card should be charged. You can see this concept end-to-end in our Stripe example app.

Auth Context & RLS#

By creating a supabase client with the auth context from the function, you can do two things:

  1. Get the user object.
  2. Run queries in the context of the user with Row Level Security (RLS) policies enforced.
supabase/functions/select-from-table-with-auth-rls/index.ts
1import { serve } from 'https://deno.land/std@0.131.0/http/server.ts'
2import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
3
4serve(async (req: Request) => {
5  try {
6    // Create a Supabase client with the Auth context of the logged in user.
7    const supabaseClient = createClient(
8      // Supabase API URL - env var exported by default.
9      Deno.env.get('SUPABASE_URL') ?? '',
10      // Supabase API ANON KEY - env var exported by default.
11      Deno.env.get('SUPABASE_ANON_KEY') ?? '',
12      // Create client with Auth context of the user that called the function.
13      // This way your row-level-security (RLS) policies are applied.
14      { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
15    )
16    // Now we can get the session or user object
17    const {
18      data: { user },
19    } = await supabaseClient.auth.getUser()
20
21    // And we can run queries in the context of our authenticated user
22    const { data, error } = await supabaseClient.from('users').select('*')
23    if (error) throw error
24
25    return new Response(JSON.stringify({ user, data }), {
26      headers: { 'Content-Type': 'application/json' },
27      status: 200,
28    })
29  } catch (error) {
30    return new Response(JSON.stringify({ error: error.message }), {
31      headers: { 'Content-Type': 'application/json' },
32      status: 400,
33    })
34  }
35})

See the example on GitHub.