tutorial··5 min read·WoWSQL Team

Astro Backend with Postgres, Auth and REST

Build an Astro 7 backend with Postgres, auth and REST: httpOnly session cookies in middleware, server endpoints, RLS per user and a server-only admin key.

The simplest Astro backend keeps your marketing pages static and renders only the signed-in pages on demand: middleware reads an httpOnly session cookie, server endpoints handle forms, and Postgres Row Level Security decides which rows each user can see. WoWSQL supplies that backend (Postgres, auth with email, magic links and OAuth, and an auto-generated REST API) without a server to run, from $0 a month. This tutorial builds a small bookmarks app on Astro 7 with sign-up, per-user data and an admin endpoint, and it keeps the service key out of the browser.

How we tested: every file below passed astro check (0 errors) and astro build on Astro 7.4.14 with @astrojs/node 11.1.15 and @wowsql/sdk 3.10.0 on 2 December 2026. We then ran the production server against a local stand-in for WoWSQL: a mock of the auth endpoints the SDK calls, in front of a real PostgREST and PostgreSQL 17 with the RLS policies below. We did not run it against a live WoWSQL project, so test on yours before you ship.

Key facts

  • Astro DB is gone: @astrojs/db was deprecated in Astro 6.4 and removed in Astro 7.0. Astro's upgrade guide suggests Node's built-in SQLite, Drizzle ORM or another database library instead (Astro v7 upgrade guide, checked 2 Dec 2026).
  • On-demand rendering needs an adapter. Pages are prerendered by default; add an adapter (Node, Vercel, Netlify or Cloudflare) and set export const prerender = false on the routes that need cookies (Astro on-demand rendering, checked 2 Dec 2026).
  • WoWSQL REST: PostgREST at https://<project>.wowsqlconnect.com/rest/v1. Send the anon key (wowsql_anon_…) in apikey and the user's JWT in Authorization: Bearer so RLS applies. The service key bypasses RLS: server only. There is no GraphQL API.
  • WoWSQL Auth: email and password, magic links, email or phone OTP, OAuth with 19 working providers, TOTP two-factor and optional Cloudflare Turnstile CAPTCHA (auth docs). Access tokens last 24 hours by default.
  • SDK: @wowsql/sdk 3.10.0 (latest on npm on 2 December 2026) with ProjectAuthClient, WowSQLClient and WowSQLStorage (TypeScript SDK docs).
  • Plans (pricing): Free $0 (1 project, 256 MB database, 512 MB files, 10,000 MAU); Pro $25/month (dedicated Postgres, 10 GB database, 100,000 MAU, daily backups kept 7 days); Scale $99/month (2,000,000 MAU, custom domains). Regions: Mumbai, US East and Frankfurt.

The architecture

/                (prerendered HTML, no cookies, served from the CDN)
/login, /app/*   (rendered on demand)
   │
   ├── src/middleware.ts ── reads wowsql_access / wowsql_refresh (httpOnly cookies)
   │                        └── ProjectAuthClient.getUser() / refreshSession()
   ├── src/pages/api/*.ts ── form posts: sign in, sign out, create, delete
   └── REST with the user's JWT ──> WoWSQL Postgres (RLS: only your rows)

Why this shape suits Astro:

  • Most of an Astro site stays static. Only /login, /app and /api/* opt out of prerendering, so the landing page keeps its CDN speed.
  • No tokens in JavaScript. httpOnly cookies can't be read by scripts, and Astro pages ship zero client JS unless you add an island.
  • Forms work without JavaScript. Plain <form method="POST"> to an endpoint, then a 303 redirect.
  • Built-in CSRF check. security.checkOrigin is on by default and returns 403 for cross-site form posts to on-demand routes (Astro config reference, checked 2 Dec 2026). In our test, a POST with Origin: https://evil.example got 403.

Step 1: Create the project and table

Create a project at app.wowsql.com/signup in the region nearest your users: Mumbai (ap-south-1), US East (us-east-1) or Frankfurt (eu-central-1). The REST Data API is off by default for new projects; if a call returns 403 with DATA_API_DISABLED, enable it in project settings and expose the table (Compute docs). Then run:

create table public.bookmarks (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null default auth.uid(),
  url text not null check (url ~ '^https?://'),
  title text not null check (char_length(title) between 1 and 200),
  created_at timestamptz not null default now()
);

alter table public.bookmarks enable row level security;

create policy "read own bookmarks"   on public.bookmarks for select using (user_id = auth.uid());
create policy "insert own bookmarks" on public.bookmarks for insert with check (user_id = auth.uid());
create policy "delete own bookmarks" on public.bookmarks for delete using (user_id = auth.uid());

grant select, insert, delete on public.bookmarks to authenticated;

user_id defaults to auth.uid(), so the app never sends it and can't forge it. More on policies in What is Row Level Security?.

Step 2: Create the Astro app and configure env

npm create astro@latest my-bookmarks -- --template minimal
cd my-bookmarks
npx astro add node
npm install @wowsql/sdk@3.10.0

Declare the variables with astro:env, so Astro checks them and keeps the secret one server-side:

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

export default defineConfig({
  adapter: node({ mode: 'standalone' }), // or the Vercel, Netlify or Cloudflare adapter
  env: {
    schema: {
      WOWSQL_URL: envField.string({ context: 'server', access: 'public' }), // https://myproject.wowsqlconnect.com
      WOWSQL_ANON_KEY: envField.string({ context: 'server', access: 'public' }), // wowsql_anon_...
      WOWSQL_SERVICE_KEY: envField.string({ context: 'server', access: 'secret', optional: true }), // bypasses RLS
    },
  },
});
# .env (never commit this file)
WOWSQL_URL=https://myproject.wowsqlconnect.com
WOWSQL_ANON_KEY=wowsql_anon_your_key_here
WOWSQL_SERVICE_KEY=wowsql_service_your_key_here

One thing we hit: variables with access: 'public' are inlined at build time, so astro build fails with an invalid-variables error if WOWSQL_URL and WOWSQL_ANON_KEY aren't set when you build. access: 'secret' values are read at runtime (Astro environment variables, checked 2 Dec 2026). Neither the URL nor the anon key is secret, but we keep them in context: 'server' because only server code calls WoWSQL in this design.

Step 3: A server-side WoWSQL module

// src/lib/wowsql.ts: imported only by middleware, endpoints and page frontmatter (server code)
import { ProjectAuthClient, WowSQLClient } from '@wowsql/sdk';
import type { AstroCookies } from 'astro';
import { WOWSQL_URL, WOWSQL_ANON_KEY, WOWSQL_SERVICE_KEY } from 'astro:env/server';

// A new auth client per request: ProjectAuthClient remembers the last session in memory.
export const authClient = () => new ProjectAuthClient({ projectUrl: WOWSQL_URL, apiKey: WOWSQL_ANON_KEY });

const cookieOpts = { path: '/', httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60 * 60 * 24 * 30 } as const;

export function setSession(cookies: AstroCookies, s: { accessToken: string; refreshToken: string }) {
  cookies.set('wowsql_access', s.accessToken, cookieOpts);
  cookies.set('wowsql_refresh', s.refreshToken, cookieOpts);
}

export function clearSession(cookies: AstroCookies) {
  cookies.delete('wowsql_access', { path: '/' });
  cookies.delete('wowsql_refresh', { path: '/' });
}

// REST as the signed-in user: anon key + the user's JWT, so Row Level Security applies.
export async function rest<T>(accessToken: string, path: string, init: RequestInit = {}): Promise<T> {
  const res = await fetch(`${WOWSQL_URL}/rest/v1/${path}`, {
    ...init,
    headers: {
      apikey: WOWSQL_ANON_KEY,
      Authorization: `Bearer ${accessToken}`,
      'Content-Type': 'application/json',
      ...init.headers,
    },
  });
  const text = await res.text();
  if (!res.ok) throw new Error(`WoWSQL ${res.status}: ${text}`);
  return (text ? JSON.parse(text) : null) as T;
}

// Service key client: bypasses RLS. Admin jobs only, never for normal user reads.
export function adminDb() {
  if (!WOWSQL_SERVICE_KEY) throw new Error('WOWSQL_SERVICE_KEY is not set');
  return new WowSQLClient({ projectUrl: WOWSQL_URL, apiKey: WOWSQL_SERVICE_KEY });
}

Two details matter:

  • A new auth client per request. In SDK 3.10.0, ProjectAuthClient keeps the last session in memory and getUser() without a token falls back to it. A shared instance on a server could answer one request with another user's session.
  • Named imports. We import { ProjectAuthClient, WowSQLClient } rather than the default export, which failed under plain Node.js ES modules in our earlier tests because the package ships CommonJS only.

Type the locals the middleware sets:

// src/env.d.ts
declare namespace App {
  interface Locals {
    user: import('@wowsql/sdk').AuthUser | null;
    accessToken: string | null;
  }
}

Step 4: Middleware: read, refresh and guard the session

// src/middleware.ts: runs before every on-demand page and endpoint
import { defineMiddleware } from 'astro:middleware';
import { authClient, setSession, clearSession } from './lib/wowsql';

export const onRequest = defineMiddleware(async (context, next) => {
  context.locals.user = null;
  context.locals.accessToken = null;
  if (context.isPrerendered) return next(); // static pages have no cookies

  const access = context.cookies.get('wowsql_access')?.value;
  const refresh = context.cookies.get('wowsql_refresh')?.value;
  const auth = authClient();

  if (access) {
    try {
      context.locals.user = await auth.getUser(access); // GET /api/auth/me
      context.locals.accessToken = access;
    } catch {
      // expired or revoked: try the refresh token below
    }
  }

  if (!context.locals.user && refresh) {
    try {
      const { session } = await auth.refreshSession(refresh);
      if (session) {
        setSession(context.cookies, session);
        context.locals.user = await auth.getUser(session.accessToken);
        context.locals.accessToken = session.accessToken;
      }
    } catch {
      clearSession(context.cookies);
    }
  }

  // Guard everything under /app
  if (context.url.pathname.startsWith('/app') && !context.locals.user) {
    return context.redirect('/login', 303);
  }
  return next();
});

context.isPrerendered skips the work for static pages, which are built once and have no request cookies. In our test, an expired access cookie plus a valid refresh cookie produced a signed-in page and two fresh Set-Cookie headers, and an anonymous request to /app got a 303 to /login. The middleware calls GET /api/auth/me once per request; cache the user for the life of the access token if that's too chatty.

Step 5: Sign-in and sign-out endpoints

// src/pages/api/auth/signin.ts
import type { APIRoute } from 'astro';
import { authClient, setSession } from '../../../lib/wowsql';

export const prerender = false;

export const POST: APIRoute = async ({ request, cookies, redirect }) => {
  const form = await request.formData();
  const email = String(form.get('email') ?? '').trim();
  const password = String(form.get('password') ?? '');
  const mode = form.get('mode') === 'signup' ? 'signup' : 'login';
  const back = (msg: string) => redirect(`/login?error=${encodeURIComponent(msg)}`, 303);

  if (!email || password.length < 8) return back('Email and an 8+ character password are required.');

  try {
    const auth = authClient();
    const res = mode === 'signup' ? await auth.signUp({ email, password }) : await auth.signIn({ email, password });
    if (res.requires2fa) return back('This account uses 2FA. Add a TOTP step first.');
    if (!res.session) return back('Check your inbox to verify your email, then sign in.');
    setSession(cookies, res.session);
  } catch (e) {
    return back(e instanceof Error ? e.message : 'Sign-in failed');
  }
  return redirect('/app', 303);
};
// src/pages/api/auth/signout.ts
import type { APIRoute } from 'astro';
import { authClient, clearSession } from '../../../lib/wowsql';

export const prerender = false;

export const POST: APIRoute = async ({ cookies, locals, redirect }) => {
  if (locals.accessToken) await authClient().logout(locals.accessToken).catch(() => {});
  clearSession(cookies);
  return redirect('/login', 303);
};
---
// src/pages/login.astro
export const prerender = false;
if (Astro.locals.user) return Astro.redirect('/app', 303);
const error = Astro.url.searchParams.get('error');
---
<html lang="en">
  <head><meta charset="utf-8" /><title>Sign in</title></head>
  <body>
    <form method="POST" action="/api/auth/signin">
      <input name="email" type="email" placeholder="you@example.com" required />
      <input name="password" type="password" minlength="8" required />
      <button name="mode" value="login">Sign in</button>
      <button name="mode" value="signup">Create account</button>
    </form>
    {error && <p role="alert">{error}</p>}
  </body>
</html>

One form serves both actions: the clicked button's name="mode" value tells the endpoint whether to sign in or sign up. If your project requires email verification, signUp returns no session and the user sees "check your inbox". For Google or GitHub sign-in, follow Add social login with OAuth and set the same two cookies in a callback endpoint.

Step 6: Read and write data as the user

---
// src/pages/app/index.astro: rendered per request, data loaded as the user
import { rest } from '../../lib/wowsql';
export const prerender = false;

type Bookmark = { id: string; url: string; title: string; created_at: string };
const { user, accessToken } = Astro.locals; // middleware already redirected anonymous visitors
// RLS returns only this user's rows: no user_id filter needed, and none can be forged
const bookmarks = await rest<Bookmark[]>(accessToken!, 'bookmarks?select=id,url,title,created_at&order=created_at.desc&limit=100');
---
<html lang="en">
  <head><meta charset="utf-8" /><title>Your bookmarks</title></head>
  <body>
    <p>Signed in as {user?.email}</p>
    <form method="POST" action="/api/auth/signout"><button>Sign out</button></form>

    <form method="POST" action="/api/bookmarks">
      <input name="url" type="url" placeholder="https://..." required />
      <input name="title" maxlength="200" placeholder="Title (optional)" />
      <button>Save</button>
    </form>

    <ul>
      {bookmarks.map((b) => (
        <li>
          <a href={b.url} rel="noopener noreferrer">{b.title}</a>
          <form method="POST" action="/api/bookmarks">
            <input type="hidden" name="_action" value="delete" />
            <input type="hidden" name="id" value={b.id} />
            <button>Delete</button>
          </form>
        </li>
      ))}
    </ul>
  </body>
</html>
// src/pages/api/bookmarks.ts: create and delete, as the signed-in user
import type { APIRoute } from 'astro';
import { rest } from '../../lib/wowsql';

export const prerender = false;

export const POST: APIRoute = async ({ request, locals, redirect }) => {
  if (!locals.accessToken) return new Response('Unauthorized', { status: 401 });
  const form = await request.formData();

  if (form.get('_action') === 'delete') {
    const id = String(form.get('id') ?? '');
    await rest(locals.accessToken, `bookmarks?id=eq.${encodeURIComponent(id)}`, { method: 'DELETE' });
    return redirect('/app', 303);
  }

  const url = String(form.get('url') ?? '').trim();
  const title = String(form.get('title') ?? '').trim() || url;
  if (!/^https?:\/\//.test(url) || title.length > 200) return redirect('/app?error=invalid', 303);
  // user_id defaults to auth.uid() in the table, so we never send it
  await rest(locals.accessToken, 'bookmarks', { method: 'POST', body: JSON.stringify({ url, title }) });
  return redirect('/app', 303);
};

The page calls rest() in its frontmatter, so the HTML arrives with the user's bookmarks already in it. In our test a second user saw an empty list, and their attempt to delete the first user's bookmark by ID returned a redirect but deleted nothing, because RLS matched zero rows.

Step 7: Use the service key in exactly one place

// src/pages/api/admin/stats.ts: the one place the service key is used
import type { APIRoute } from 'astro';
import { adminDb } from '../../../lib/wowsql';

export const prerender = false;
const ADMINS = new Set(['you@yourcompany.com']);

export const GET: APIRoute = async ({ locals }) => {
  if (!locals.user || !ADMINS.has(locals.user.email)) return new Response('Admins only', { status: 403 });
  const db = adminDb();
  // Service key: counts every user's bookmarks, ignoring RLS. Only the number leaves the server.
  const total = await db.table('bookmarks').count();
  return Response.json({ total });
};

We checked the client output (dist/client) after astro build: it contains neither the service key nor its variable name. A non-admin got 403; the admin got {"total":1}, a count across every user that only the service key can see.

What about live updates and islands?

If you add a React, Svelte or Vue island that needs live data, it can open a WoWSQL Realtime WebSocket with the anon key. Per the realtime docs, change events can't be filtered by RLS, so anon and signed-in clients can only subscribe to tables without RLS; tables with RLS need the service key on a server. For private data like bookmarks, stream a content-free "something changed" table and refetch through your endpoint, as in Build a realtime chat app with Postgres. Typing and online indicators use broadcast and presence instead; see Typing indicators and online presence.

Astro backend options compared

WoWSQL Supabase Astro DB Your own Postgres + an auth library
Status in Astro 7 Works through endpoints and middleware (this guide) Official Astro guide in the Astro docs Removed in Astro 7.0 Works
What you get Postgres, auth, storage, realtime, auto REST Postgres, auth, storage, realtime, auto REST Was a SQLite/libSQL integration Only what you build
Session handling You write the cookie code (above) Astro's guide sets sb-access-token cookies with only path: "/" Not applicable Depends on the library
Free tier 1 project, 256 MB, 10,000 MAU 2 projects, 500 MB, 50,000 MAU Not applicable Your server costs
Regions Mumbai, US East, Frankfurt Many AWS regions Not applicable Anywhere

Sources checked 2 Dec 2026: Astro: Supabase & Astro, Astro: backend services, Astro DB removal, Supabase pricing, WoWSQL pricing.

Where others are better: Supabase is listed in Astro's own backend guides and has a larger free tier (two projects, 500 MB, 50,000 MAU). If you only need a local database for a Node-hosted site, Astro's upgrade guide points to Node's built-in node:sqlite, which needs no service at all. WoWSQL's case is one flat plan covering database, auth, storage and realtime, regions in Mumbai, US East and Frankfurt, and the httpOnly-cookie pattern above. (Astro's Supabase example stores tokens in cookies without httpOnly; if you follow it, add httpOnly, secure and sameSite yourself.)

Related guides

FAQ

What is the best backend for an Astro site?

For a content site with a few signed-in pages, use a hosted Postgres backend with auth and call it from Astro middleware and server endpoints, keeping the rest of the site static. WoWSQL, Supabase, or your own Postgres plus an auth library all fit; pick on free-tier size, regions and how much session code you want to write.

Does Astro have a built-in database?

Not any more. Astro DB (@astrojs/db) was deprecated in Astro 6.4 and removed in Astro 7.0. Astro now points to Node's built-in SQLite, Drizzle ORM or a hosted database.

How do I add authentication to Astro?

Render the protected routes on demand with an adapter, sign users in from a server endpoint, store the access and refresh tokens in httpOnly cookies, and check them in src/middleware.ts, putting the user on Astro.locals.

Can I use Postgres with Astro server endpoints?

Yes. Endpoints in src/pages/api/*.ts with prerender = false run on the server for every request, so they can call a Postgres REST API like WoWSQL's with the user's token, or connect with a Postgres driver if your host allows it.

Is it safe to put the WoWSQL anon key in an Astro island?

Yes, the anon key is designed for client code; RLS decides what it can read. Never put the service key in an island or in a variable with context: 'client'.

What is a good Supabase alternative for Astro?

WoWSQL works the same way from Astro (Postgres, auth, REST and realtime behind an anon key) with Mumbai, US East and Frankfurt regions and plans at $0, $25 and $99 a month. Supabase has the official Astro guide and a larger free tier.

Create a free WoWSQL project · TypeScript SDK docs · Auth docs