Skip to content
All posts

Use @supabase/server for backend route auth

DaveOTF Kit
7 min read
Use @supabase/server for backend route auth

A protected backend route has several jobs before it reaches application logic: verify who made the request, choose the right database client, preserve Row Level Security, and return a response in the format its runtime expects. Repeating that setup across handlers makes it easy for two routes to drift.

Supabase’s @supabase/server package is designed to centralize much of that request setup. It is in public beta, so check the current API and package notes before adopting it in a production service. This guide focuses on how to reason about its handler model, choose an authentication mode, and keep privileged database access deliberate.

What the package provides

The main entry point is withSupabase. It wraps a standard request handler, applies the selected authentication policy, and gives the handler a Supabase context. In a user-authenticated route, that context includes a user-scoped Supabase client and verified identity information. A separate admin client is available for privileged operations.

A minimal Deno-style handler looks like this:

import { withSupabase } from 'npm:@supabase/server'

Deno.serve(
  withSupabase({ auth: 'user' }, async (_req, ctx) => {
    const { data, error } = await ctx.supabase
      .from('todos')
      .select('id, title, completed')

    if (error) {
      return Response.json({ error: 'Could not load todos' }, { status: 500 })
    }

    return Response.json({ data })
  })
)

The important design choice is visible at the wrapper: auth: 'user' means the handler expects a valid user token. The route then queries through the user-scoped client. That client is intended to work with the database’s Row Level Security policies, so the database can apply the caller’s access rules to the query.

The wrapper does not decide what each user is allowed to read or write in your product. Your schema, policies, and application authorization still matter. Treat the package as request authentication and client setup, not as a replacement for a security review.

Choose an auth mode for each route

The package documents four single-mode choices: user, none, secret, and publishable. You can also accept a combination such as ['user', 'secret'] where the route has a clear reason to support both kinds of caller.

Use user for a route acting on behalf of a signed-in user. Use none only when the endpoint is intentionally public, such as a health response, or when another verification mechanism is responsible for the request. A public route should still validate its inputs, limit abuse where appropriate, and avoid returning private data.

Use secret for server-to-server callers that authenticate with a secret key. Use publishable when the route is meant to accept a publishable key. Those choices describe how the incoming request is authenticated; they do not automatically make every operation inside the handler safe. Validate the caller’s authority for the specific action and keep keys out of browser code, logs, and error messages.

When a route accepts more than one mode, decide explicitly which operations each mode may perform. For example, a service-to-service caller might be allowed to refresh an internal record while a user caller can only read their own row. Encode that distinction in route logic and database policies rather than assuming the wrapper inferred your business rules.

12 production screens. Login and database wired.

The SaaS Dashboard Kit includes login, a database, and a working dashboard. Live demo at saas.otf-kit.dev.

See the live demo

Keep user queries and admin work separate

The context exposes ctx.supabase and ctx.supabaseAdmin. The user-scoped client is the natural choice for ordinary user-owned reads and writes. The admin client uses service-role privileges and can bypass Row Level Security. That makes it useful for narrowly scoped administrative tasks, but dangerous as a default client for user-facing operations.

A useful review question is: “Could this query run with the caller’s user-scoped client?” If yes, prefer that client. If it truly needs elevated access, make the reason visible in the code, check the caller’s authorization before using the admin client, select only the required data, and avoid returning privileged records by accident.

Do not treat a verified JWT as permission for every action. Authentication answers who presented a valid credential; authorization answers whether that identity may perform this operation on this resource. Keep those decisions explicit. A route that authenticates correctly can still expose data if its query ignores tenant, ownership, or role boundaries.

Use the adapter that matches your runtime

withSupabase returns a standard Web API request handler, so the documented pattern applies to Supabase Edge Functions, Vercel Functions, Cloudflare Workers, Bun, and Deno environments that support Request and Response.

For Hono, Supabase documents an adapter import and puts the context on the Hono variable:

import { withSupabase } from '@supabase/server/adapters/hono'
import { Hono } from 'hono'

const app = new Hono()

app.get('/todos', withSupabase({ auth: 'user' }), async (c) => {
  const { supabase } = c.var.supabaseContext
  const { data, error } = await supabase.from('todos').select('id, title')

  if (error) return c.json({ error: 'Could not load todos' }, 500)
  return c.json({ data })
})

export default { fetch: app.fetch }

The adapter matters because a framework has its own request and context conventions. Avoid copying a Deno example into a Hono route and assuming its callback arguments are identical. Check the adapter documentation for the framework you actually deploy, then confirm the runtime’s package resolution and environment variables in a small route before migrating a larger set of handlers.

Know when this is not the right package

@supabase/server handles stateless, header-based authentication for backend handlers. Supabase describes @supabase/ssr as a separate package for cookie-based session management in frameworks such as Next.js and SvelteKit. The two packages serve different request models; the server package is not a drop-in replacement for an SSR session setup.

Also account for beta status. Pin and review the dependency version according to your release process, read the current migration and adapter notes, and exercise the exact runtime you use. Test rejected requests, malformed credentials, valid user access, and any privileged branch. Verify that user-scoped queries remain subject to the intended Row Level Security policies and that secret-key paths are not exposed to public callers.

A practical adoption sequence

Start with one low-risk route whose access policy is easy to describe. Write down whether it accepts a signed-in user, a public request, or a server credential. Wrap that route with the matching auth mode, then keep its data access on the least-privileged client that can do the job.

Next, test both sides of the boundary. A request with no credential should fail on a user-only route. A valid user should see only rows permitted by the policies. A public route should return only public information. If the route has an admin branch, test that a normal user cannot reach it by changing request fields or URL parameters.

Finally, review operational details: package version, runtime compatibility, environment variable names, error handling, and logs. A wrapper can reduce repeated setup, but it cannot tell whether your database policies reflect your product’s rules. Keep those checks in code review and automated tests.

Where an OTF starter fits

If you need a place to prototype a dashboard around backend routes, the OTF SaaS Dashboard documentation describes a separate Vite and React frontend with a Hono backend, Postgres, Drizzle, and Better Auth. It does not ship with @supabase/server or a Supabase integration. Treat it as an editable application shell, not a preconfigured Supabase solution; you would make and verify that integration yourself. The kit also does not include product billing.

For a broader checklist on reviewing application boundaries and failure cases, see our production-readiness audit for AI apps. When you are ready to start a project, open the OTF starter page and choose the base that matches your app.

An orange-hoodie character gestures toward an illustrative board showing authentication, a database, realtime, and storage.

Illustration of common backend capability categories; it is not a diagram of an OTF kit’s shipped stack.

Sources

supabasebackendkitsannouncement
OTF SaaS Dashboard Kit

Ship the product, not the setup.

  • 12 production screens — auth, team, analytics, and settings
  • Login and a real database are wired in
  • AI configs pre-tuned so your agent extends instead of regenerates
Free starter

Ship your first screen tonight — free starter in your inbox

The quickstart, the SDK repo and the live kit demos, on this screen and in your inbox.

No spam. Unsubscribe any time.

Free with your email

Get the free AI configs pack

The AI files every kit ships with. Drop them in and your AI tool knows your project.

  • CLAUDE.mdProject context
  • .cursorrulesRules for Cursor
  • prompts/Task prompts

No spam. Unsubscribe any time.