Home

Integrating With Supra Auth

Edge Functions work seamlessly with Supra 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 supra 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.
supra/functions/select-from-table-with-auth-rls/index.ts

_35
import { serve } from 'https://deno.land/std@0.177.0/http/server.ts'
_35
import { createClient } from 'https://esm.sh/@supra/supra-js@2'
_35
_35
serve(async (req: Request) => {
_35
try {
_35
// Create a Supra client with the Auth context of the logged in user.
_35
const supraClient = createClient(
_35
// Supra API URL - env var exported by default.
_35
Deno.env.get('supra_URL') ?? '',
_35
// Supra API ANON KEY - env var exported by default.
_35
Deno.env.get('supra_ANON_KEY') ?? '',
_35
// Create client with Auth context of the user that called the function.
_35
// This way your row-level-security (RLS) policies are applied.
_35
{ global: { headers: { Authorization: req.headers.get('Authorization')! } } }
_35
)
_35
// Now we can get the session or user object
_35
const {
_35
data: { user },
_35
} = await supraClient.auth.getUser()
_35
_35
// And we can run queries in the context of our authenticated user
_35
const { data, error } = await supraClient.from('users').select('*')
_35
if (error) throw error
_35
_35
return new Response(JSON.stringify({ user, data }), {
_35
headers: { 'Content-Type': 'application/json' },
_35
status: 200,
_35
})
_35
} catch (error) {
_35
return new Response(JSON.stringify({ error: error.message }), {
_35
headers: { 'Content-Type': 'application/json' },
_35
status: 400,
_35
})
_35
}
_35
})

See the example on GitHub.