🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Supabase Guide: Data, Auth and Row Level Security

Use Astro with Supabase: query Postgres at build time, add cookie-based auth with @supabase/ssr in middleware, protect pages and secure tables with row level security.

#Astro#Supabase#Database#Authentication#Postgres

To use Supabase with Astro, install @supabase/supabase-js and query your tables with supabase.from('table').select(). For static pages, run that query at build time with your project’s public key; for logins and per-user data, add an adapter, create a server client with @supabase/ssr so the session lives in cookies, and read the user in middleware. Row level security in Postgres decides what each user can see.

This guide covers both modes on Astro 7: build-time reads, cookie auth, protected pages, form actions and storage.

Key Takeaways

  • Supabase gives you Postgres, auth, file storage and realtime behind one API and client library.
  • Build-time queries work on a fully static site; auth and per-user pages need an adapter.
  • Use @supabase/ssr with getAll and setAll cookie handlers so Astro can read sessions on the server.
  • Check users with auth.getUser() on the server, which verifies the token with Supabase.
  • Turn on row level security for every table. The public key is safe only when policies are in place.

What Supabase adds to an Astro site

Supabase is a hosted backend built on PostgreSQL. A project gives you a Postgres database, an auto-generated REST API (PostgREST), authentication, file storage, realtime subscriptions and edge functions. It’s open source, so you can also self-host it.

For an Astro site, the useful split is when the query runs:

Use case When it runs Astro setup
Directory, listings, product data At build time Static, no adapter
Login, accounts, dashboards Per request Adapter + @supabase/ssr
Form submissions, comments Per request Adapter + Astro Actions or an endpoint
Live updates (chat, presence) In the browser A client-side island

Many sites mix all of these: static marketing pages, a few on-demand account pages, and one interactive island. Our Astro database options article compares Supabase with Turso, Neon, Cloudflare D1 and Astro DB if you’re still choosing.

Set up keys and the client

Install the packages:

npm install @supabase/supabase-js @supabase/ssr

In the Supabase dashboard, open Project Settings, API Keys. Copy the project URL and the publishable key (older projects label it the anon key). Both are designed to be public. Never put the secret or service_role key in client code; it bypasses row level security.

Declare the variables with astro:env so a missing value fails fast:

// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  adapter: node({ mode: 'standalone' }),
  env: {
    schema: {
      SUPABASE_URL: envField.string({ context: 'server', access: 'public' }),
      SUPABASE_KEY: envField.string({ context: 'server', access: 'public' }),
    },
  },
});

The adapter is only needed for the auth sections below. Swap @astrojs/node for the Netlify, Vercel or Cloudflare adapter to match your host. The environment variables guide explains context and access.

Query Supabase at build time

For data that changes rarely, query during the build and output static HTML. This page lists published events:

---
// src/pages/events/index.astro
import { createClient } from '@supabase/supabase-js';
import { SUPABASE_URL, SUPABASE_KEY } from 'astro:env/server';
import BaseLayout from '../../layouts/BaseLayout.astro';

const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
const { data: events, error } = await supabase
  .from('events')
  .select('id, title, slug, starts_at, city')
  .eq('published', true)
  .order('starts_at', { ascending: true });

if (error) throw new Error(`Supabase: ${error.message}`);
---
<BaseLayout title="Upcoming events">
  <h1>Upcoming events</h1>
  <ul>
    {events.map((e) => (
      <li><a href={`/events/${e.slug}/`}>{e.title}</a>, {e.city}</li>
    ))}
  </ul>
</BaseLayout>

Throwing on error matters: supabase-js returns errors instead of throwing, and a silent failure would publish an empty page. For detail pages, run the same query inside getStaticPaths(), or wrap it in a content loader so you can use getCollection(). Rebuild with a Supabase database webhook that calls your host’s deploy hook when rows change.

Generate TypeScript types so data is typed by your schema:

npx supabase gen types typescript --project-id your-project-ref > src/lib/database.types.ts

Then pass the type: createClient<Database>(SUPABASE_URL, SUPABASE_KEY).

Create a server client with @supabase/ssr

Auth needs the session on the server, which means cookies. @supabase/ssr creates a client that reads and writes its auth cookies through handlers you provide. In Astro, wire them to the request headers and Astro.cookies:

// src/lib/supabase.ts
import { createServerClient, parseCookieHeader } from '@supabase/ssr';
import type { AstroCookies } from 'astro';
import { SUPABASE_URL, SUPABASE_KEY } from 'astro:env/server';

export function createSupabase(request: Request, cookies: AstroCookies) {
  return createServerClient(SUPABASE_URL, SUPABASE_KEY, {
    cookies: {
      getAll() {
        return parseCookieHeader(request.headers.get('Cookie') ?? '').map(({ name, value }) => ({
          name,
          value: value ?? '',
        }));
      },
      setAll(cookiesToSet) {
        cookiesToSet.forEach(({ name, value, options }) => cookies.set(name, value, options));
      },
    },
  });
}

Create a new client per request. A module-level client would share one user’s session with everyone.

Read the user in middleware

Middleware runs before every on-demand page, so it’s the right place to load the user once and protect routes:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { createSupabase } from './lib/supabase';

const protectedPaths = ['/account', '/dashboard'];

export const onRequest = defineMiddleware(async (context, next) => {
  if (context.isPrerendered) return next();

  const supabase = createSupabase(context.request, context.cookies);
  const { data: { user } } = await supabase.auth.getUser();

  context.locals.supabase = supabase;
  context.locals.user = user;

  if (!user && protectedPaths.some((p) => context.url.pathname.startsWith(p))) {
    return context.redirect('/login/');
  }
  return next();
});

Type the locals so pages get autocomplete:

// src/env.d.ts
declare namespace App {
  interface Locals {
    supabase: import('@supabase/supabase-js').SupabaseClient;
    user: import('@supabase/supabase-js').User | null;
  }
}

Use getUser() rather than getSession() for access decisions on the server. getSession() reads the cookie without checking it, while getUser() validates the token with Supabase Auth. The isPrerendered check skips static pages, which have no request cookies at build time. Our Astro middleware guide covers ordering and sequence().

Sign users in with an Astro Action

Astro Actions give you a typed server function you can call from a plain HTML form. This one signs in with email and password:

// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';

export const server = {
  login: defineAction({
    accept: 'form',
    input: z.object({ email: z.email(), password: z.string().min(8) }),
    handler: async ({ email, password }, context) => {
      const { error } = await context.locals.supabase.auth.signInWithPassword({ email, password });
      if (error) throw new ActionError({ code: 'UNAUTHORIZED', message: error.message });
      return { ok: true };
    },
  }),
};
---
// src/pages/login.astro
import { actions } from 'astro:actions';

export const prerender = false;

const result = Astro.getActionResult(actions.login);
if (result && !result.error) return Astro.redirect('/account/');
---
<form method="POST" action={actions.login}>
  <label>Email <input name="email" type="email" required /></label>
  <label>Password <input name="password" type="password" required /></label>
  {result?.error && <p role="alert">{result.error.message}</p>}
  <button>Sign in</button>
</form>

signInWithPassword() sets the auth cookies through your setAll handler, so the next request’s middleware sees the user. For OAuth, call signInWithOAuth({ provider: 'github', options: { redirectTo } }), redirect to the returned data.url, and add a callback endpoint that calls exchangeCodeForSession(code). The Astro Actions guide explains form handling and errors in detail.

Protect data with row level security

Pages are only half the job. The public key can call your REST API from anywhere, so every table needs row level security (RLS) with policies:

-- Supabase SQL editor
alter table public.notes enable row level security;

create policy "Users read their own notes"
  on public.notes for select
  using (auth.uid() = user_id);

create policy "Users insert their own notes"
  on public.notes for insert
  with check (auth.uid() = user_id);

Now locals.supabase.from('notes').select() returns only the signed-in user’s rows, because the server client sends that user’s token. A protected page becomes simple:

---
// src/pages/account/notes.astro
export const prerender = false;
const { data: notes } = await Astro.locals.supabase
  .from('notes')
  .select('id, body, created_at')
  .order('created_at', { ascending: false });
---
<h1>Your notes</h1>
<ul>{notes?.map((n) => <li>{n.body}</li>)}</ul>

For a public table like events, add a select policy that allows reads of published rows only: using (published = true). The Supabase dashboard flags tables that have RLS disabled; treat that warning as a bug.

Storage, realtime and hosting

Storage. Public buckets serve files at https://<project>.supabase.co/storage/v1/object/public/<bucket>/<path>, and supabase.storage.from(bucket).getPublicUrl(path) builds that URL for you. Add the Supabase domain to image.domains to optimize them with <Image /> from astro:assets.

Realtime. Live subscriptions run in the browser, so put them in a framework component with a client:* directive and keep the rest of the page static.

Hosting. Static pages deploy anywhere. On-demand routes need an adapter, and Supabase works on Node, Netlify, Vercel and Cloudflare because supabase-js uses fetch. Our Astro SSR guide covers mixing prerendered and on-demand pages, and the official Astro Supabase guide has more examples.

If the public pages are the bigger job, starting from a SaaS and technology theme gives you the marketing site, and you add the Supabase-backed account pages on top.

FAQ

Can I use Supabase with a static Astro site?

Yes, for reading data. Query Supabase at build time in page frontmatter, getStaticPaths() or a content loader, and the output is plain HTML. Logins, per-user pages and form writes need an adapter so code runs on each request.

Is it safe to expose the Supabase anon or publishable key?

Yes, as long as every table has row level security enabled with correct policies. The key identifies your project but grants only what your policies allow. The secret or service_role key bypasses RLS and must stay on the server.

Should I use getSession or getUser in Astro middleware?

Use getUser() (or getClaims() on newer supabase-js versions) for anything that grants access. getSession() returns whatever is in the cookie without verifying it, so a tampered cookie could pass. getUser() checks the token with Supabase Auth.

Do I need @supabase/ssr or is supabase-js enough?

supabase-js alone is enough for build-time queries and browser-only code. For server-rendered pages that need the logged-in user, @supabase/ssr stores the session in cookies the server can read, which supabase-js does not do by default.

Which Astro adapter works best with Supabase?

Any of them. Supabase’s client talks to its API over HTTPS with fetch, so it runs on the Node, Netlify, Vercel and Cloudflare adapters. Pick the adapter for the host you already use.