On this page

Authentication

By default a function only runs for requests with a valid JWT of your project.

#JWT verification (default on)

With Require a valid JWT on, a request must carry Authorization: Bearer <token> where the token is your anon key, the service role key, or the access token of a signed-in user. The signature and expiry are checked before your code runs; invalid requests get 401 and are not counted as invocations. The SDK sends the right header for you: the user's token when someone is signed in, otherwise the anon key.

The anon key only proves the request comes from your app. To know who is calling, read the user from the token and query as that user:

TypeScript
import { createClient } from 'https://stitchdb.com/sdk/stitchdb-js.mjs'

Deno.serve(async (req) => {
  // Queries run as the caller: Row Level Security applies.
  const db = createClient(Deno.env.get('STITCHDB_URL')!, Deno.env.get('STITCHDB_ANON_KEY')!, {
    global: { headers: { Authorization: req.headers.get('Authorization') ?? '' } },
    auth: { persistSession: false },
  })
  const { data: { user } } = await db.auth.getUser()
  if (!user) return Response.json({ error: 'Sign in first' }, { status: 401 })
  const { data } = await db.from('todos').select('*')
  return Response.json(data)
})

Middleware does the same in one line: pipeline([withClaims(), withRequiredClaims(), withStitchClient()], handler).

#Public functions (verification off)

Turn the switch off in the function's Settings (or deploy with "verify_jwt": false) for callers that can't send your keys, such as Stripe, GitHub or other webhooks. Anyone with the URL can then call the function, so check the request yourself, for example with the sender's signature or a shared token:

TypeScript
// A public function (JWT verification off) still gets the caller's headers:
Deno.serve((req) => {
  if (req.headers.get('x-webhook-token') !== Deno.env.get('WEBHOOK_TOKEN')) {
    return new Response('Forbidden', { status: 403 })
  }
  return new Response('ok')
})
Was this helpful?