The cleanest SvelteKit backend keeps every database call in server code (+page.server.ts load functions and form actions), stores the user's session in httpOnly cookies, and lets Postgres Row Level Security decide which rows each user sees. WoWSQL gives you that backend without running servers: a Postgres database, email and OAuth auth, and an auto-generated REST API, from $0 a month. This tutorial builds a small notes app on SvelteKit 3 with sign-up, sign-in, per-user data and an admin page, and it keeps the service key out of the browser.
Every file below was type-checked with svelte-check and built with vite build on SvelteKit 3.4.1 and @wowsql/sdk 3.10.0 on 29 November 2026. We then ran the production build against a local stand-in for WoWSQL (a mock of the auth endpoints plus a real PostgREST and PostgreSQL 17 server with the RLS policies below). We did not run it against a live WoWSQL project, so test on yours before you ship.
Key facts
- WoWSQL REST: an auto-generated PostgREST API at
https://<project>.wowsqlconnect.com/rest/v1. Send the anon key (wowsql_anon_…) inapikeyand the user's JWT inAuthorization: Bearerso RLS applies. The service key bypasses RLS: server only. There is no GraphQL API.- WoWSQL Auth: email and password, magic links, phone OTP, OAuth with 19 working providers, TOTP two-factor and optional Cloudflare Turnstile CAPTCHA (auth docs).
- SDK:
@wowsql/sdk3.10.0 (latest on npm on 29 November 2026) withProjectAuthClient,WowSQLClientandWowSQLStorage. Docs also cover Python, Go, Java, PHP, Ruby, Rust, Swift, Flutter/Dart, Kotlin and C# (SDK docs).- SvelteKit 3: private variables come from
$app/env/private, defined insrc/env.ts;$libbecame#lib;$env/*is deprecated (migration guide).- 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).
The architecture in one picture
Browser ──(form posts, page loads)──> SvelteKit server ──(REST + user JWT)──> WoWSQL Postgres (RLS)
│ │
└── httpOnly cookies: wowsql_access, └── service key: only in #lib/server, only for admin jobs
wowsql_refresh (never readable by JS)
Why server-first in SvelteKit:
- No tokens in JavaScript. httpOnly cookies can't be read by scripts, which limits the damage from an XSS bug.
- Pages render with data. Load functions run on the server, so the first HTML already contains the user's notes.
- Forms work without JavaScript. Form actions with
use:enhanceadd a smooth experience on top. - Secrets stay put. SvelteKit refuses to bundle server-only modules into browser code. We tested this: importing our server module from a
.sveltefile fails the build withserver_only_import.
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 Compute docs note that the REST Data API is off by default for new projects. If a REST call returns 403 with DATA_API_DISABLED, enable the Data API in your project settings and expose the table.
Run this in the SQL editor:
create table public.notes (
id uuid primary key default gen_random_uuid(),
user_id uuid not null default auth.uid(),
title text not null check (char_length(title) between 1 and 200),
created_at timestamptz not null default now()
);
alter table public.notes enable row level security;
create policy "read own notes" on public.notes for select using (user_id = auth.uid());
create policy "insert own notes" on public.notes for insert with check (user_id = auth.uid());
create policy "delete own notes" on public.notes for delete using (user_id = auth.uid());
grant select, insert, delete on public.notes to authenticated;
user_id defaults to auth.uid(), so the app never sends it, and the insert policy rejects any attempt to write a note for someone else. For more on policies, see What is Row Level Security?.
Step 2: Create the SvelteKit app and environment
npx sv create my-notes --template minimal --types ts
cd my-notes
npm install @wowsql/sdk@3.10.0
SvelteKit 3 reads environment variables through src/env.ts. Anything without public: true is private and can only be imported on the server:
// src/env.ts
import { defineEnvVars } from '@sveltejs/kit/env';
export const variables = defineEnvVars({
WOWSQL_URL: { public: true }, // https://myproject.wowsqlconnect.com
WOWSQL_ANON_KEY: { public: true }, // wowsql_anon_... (safe to expose)
WOWSQL_SERVICE_KEY: {} // wowsql_service_... (private: server only, 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
On SvelteKit 2, use $env/static/private and $env/static/public with PUBLIC_-prefixed names, and $lib instead of #lib. The rest of this tutorial is the same.
Step 3: A server-only WoWSQL module
Put this in src/lib/server/ so SvelteKit treats it as server-only. The #lib alias comes from the imports field the SvelteKit 3 template adds to package.json.
// src/lib/server/wowsql.ts
// Server-only: SvelteKit refuses to bundle this file (or $app/env/private) into browser code.
import { ProjectAuthClient, WowSQLClient } from '@wowsql/sdk';
import { WOWSQL_URL, WOWSQL_ANON_KEY } from '$app/env/public';
import { WOWSQL_SERVICE_KEY } from '$app/env/private';
// One auth client per request. ProjectAuthClient keeps the last session in memory,
// so a shared instance on a server could hand one user's tokens to another request.
export const authClient = () => new ProjectAuthClient({ projectUrl: WOWSQL_URL, apiKey: WOWSQL_ANON_KEY });
// REST as the signed-in user: anon key + user's JWT, so Row Level Security applies.
export async function rest<T>(
fetchFn: typeof fetch,
accessToken: string,
path: string,
init: RequestInit = {}
): Promise<T> {
const res = await fetchFn(`${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. Only for admin jobs, never for normal user reads.
export const adminDb = new WowSQLClient({ projectUrl: WOWSQL_URL, apiKey: WOWSQL_SERVICE_KEY });
Two details matter here:
- A new auth client per request. In SDK 3.10.0,
ProjectAuthClientremembers the last session it saw in memory, andgetUser()without a token falls back to it. On a server that handles many users, a shared instance could answer one request with another user's session. Creating a client per request costs almost nothing and removes the risk. - Named imports. We import
{ WowSQLClient }rather than the default export. In our test, the default import failed under plain Node.js ES modules with "WowSQLClient is not a constructor", because the package ships CommonJS only. Named imports worked in Node and in the Vite build.
Step 4: Read the session in a hook
hooks.server.ts runs before every request. It checks the access cookie, refreshes it when it has expired, and puts the user on event.locals:
// src/app.d.ts
import type { AuthUser } from '@wowsql/sdk';
declare global {
namespace App {
interface Locals {
user: AuthUser | null;
accessToken: string | null;
}
}
}
export {};
// src/hooks.server.ts
import type { Handle } from '@sveltejs/kit/hooks';
import { authClient } from '#lib/server/wowsql.js';
const cookieOpts = { path: '/', httpOnly: true, sameSite: 'lax', secure: true } as const;
export const handle: Handle = async ({ event, resolve }) => {
event.locals.user = null;
event.locals.accessToken = null;
const access = event.cookies.get('wowsql_access');
const refresh = event.cookies.get('wowsql_refresh');
const auth = authClient();
if (access) {
try {
event.locals.user = await auth.getUser(access); // GET /api/auth/me
event.locals.accessToken = access;
} catch {
// expired or revoked: fall through to refresh
}
}
if (!event.locals.user && refresh) {
try {
const { session } = await auth.refreshSession(refresh);
if (session) {
event.cookies.set('wowsql_access', session.accessToken, cookieOpts);
event.cookies.set('wowsql_refresh', session.refreshToken, cookieOpts);
event.locals.user = await auth.getUser(session.accessToken);
event.locals.accessToken = session.accessToken;
}
} catch {
event.cookies.delete('wowsql_access', { path: '/' });
event.cookies.delete('wowsql_refresh', { path: '/' });
}
}
return resolve(event);
};
In SvelteKit 3 the Handle type lives in @sveltejs/kit/hooks. The hook calls GET /api/auth/me once per request; if that's too chatty for your traffic, cache the user for the life of the access token.
Step 5: Sign-up and sign-in with form actions
// src/routes/login/+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { authClient } from '#lib/server/wowsql.js';
const cookieOpts = { path: '/', httpOnly: true, sameSite: 'lax', secure: true } as const;
async function start(cookies: import('@sveltejs/kit').Cookies, form: FormData, mode: 'login' | 'signup') {
const email = String(form.get('email') ?? '').trim();
const password = String(form.get('password') ?? '');
if (!email || password.length < 8) return fail(400, { email, error: 'Email and an 8+ character password are required.' });
const auth = authClient();
try {
const res = mode === 'signup' ? await auth.signUp({ email, password }) : await auth.signIn({ email, password });
if (res.requires2fa) return fail(400, { email, error: 'This account uses 2FA. Add a TOTP step first.' });
if (!res.session) return fail(400, { email, error: 'Check your inbox to verify your email, then sign in.' });
cookies.set('wowsql_access', res.session.accessToken, cookieOpts);
cookies.set('wowsql_refresh', res.session.refreshToken, cookieOpts);
} catch (e) {
return fail(400, { email, error: e instanceof Error ? e.message : 'Sign-in failed' });
}
redirect(303, '/notes');
}
export const actions: Actions = {
login: ({ request, cookies }) => request.formData().then((f) => start(cookies, f, 'login')),
signup: ({ request, cookies }) => request.formData().then((f) => start(cookies, f, 'signup'))
};
<!-- src/routes/login/+page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
import type { PageProps } from './$types';
let { form }: PageProps = $props();
</script>
<form method="POST" action="?/login" use:enhance>
<input name="email" type="email" value={form?.email ?? ''} placeholder="you@example.com" required />
<input name="password" type="password" minlength="8" required />
<button>Sign in</button>
<button formaction="?/signup">Create account</button>
{#if form?.error}<p role="alert">{form.error}</p>{/if}
</form>
If your project requires email verification, signUp returns no session and the form shows the "check your inbox" message. To add Google or GitHub sign-in, follow Add social login with OAuth and set the same two cookies in your callback route.
Sign-out is a one-line action:
// src/routes/logout/+page.server.ts
import { redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { authClient } from '#lib/server/wowsql.js';
export const actions: Actions = {
default: async ({ cookies, locals }) => {
if (locals.accessToken) await authClient().logout(locals.accessToken).catch(() => {});
cookies.delete('wowsql_access', { path: '/' });
cookies.delete('wowsql_refresh', { path: '/' });
redirect(303, '/login');
}
};
Step 6: Load and change data as the user
// src/routes/notes/+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { rest } from '#lib/server/wowsql.js';
type Note = { id: string; title: string; created_at: string };
export const load: PageServerLoad = async ({ locals, fetch }) => {
if (!locals.user || !locals.accessToken) redirect(303, '/login');
// RLS returns only this user's rows: no user_id filter needed, and none can be forged
const notes = await rest<Note[]>(fetch, locals.accessToken, 'notes?select=id,title,created_at&order=created_at.desc&limit=50');
return { email: locals.user.email, notes };
};
export const actions: Actions = {
create: async ({ request, locals, fetch }) => {
if (!locals.accessToken) redirect(303, '/login');
const title = String((await request.formData()).get('title') ?? '').trim();
if (!title || title.length > 200) return fail(400, { title, error: 'Title must be 1-200 characters.' });
await rest(fetch, locals.accessToken, 'notes', { method: 'POST', body: JSON.stringify({ title }) });
},
delete: async ({ request, locals, fetch }) => {
if (!locals.accessToken) redirect(303, '/login');
const id = String((await request.formData()).get('id') ?? '');
await rest(fetch, locals.accessToken, `notes?id=eq.${encodeURIComponent(id)}`, { method: 'DELETE' });
}
};
<!-- src/routes/notes/+page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
import type { PageProps } from './$types';
let { data, form }: PageProps = $props();
</script>
<p>Signed in as {data.email}</p>
<form method="POST" action="/logout"><button>Sign out</button></form>
<form method="POST" action="?/create" use:enhance>
<input name="title" value={form?.title ?? ''} maxlength="200" required />
<button>Add note</button>
{#if form?.error}<p role="alert">{form.error}</p>{/if}
</form>
<ul>
{#each data.notes as note (note.id)}
<li>
{note.title}
<form method="POST" action="?/delete" use:enhance>
<input type="hidden" name="id" value={note.id} />
<button>Delete</button>
</form>
</li>
{/each}
</ul>
The load function passes SvelteKit's fetch to the helper, so requests show up in SvelteKit's tooling. In our test, a second user signed in and saw an empty list, because RLS hid the first user's note even though both used the same query.
Step 7: Use the service key only where you must
The service key bypasses every policy, so treat it like a database password. A typical legitimate use is an admin page that reports totals:
// src/routes/admin/+page.server.ts
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { adminDb } from '#lib/server/wowsql.js';
const ADMINS = new Set(['you@yourcompany.com']);
export const load: PageServerLoad = async ({ locals }) => {
if (!locals.user || !ADMINS.has(locals.user.email)) error(403, 'Admins only');
// Service key: counts every user's notes, ignoring RLS. Only the number leaves the server.
const totalNotes = await adminDb.table('notes').count();
return { totalNotes };
};
We checked that the production client bundle contains neither the service key nor its variable name. Never use adminDb to fetch data for a normal user "and filter it in code": one forgotten filter leaks every row.
What about live updates?
WoWSQL Realtime works over a WebSocket authenticated with the anon key. Per WoWSQL's realtime service code, change events can't be filtered per row, so the service only lets anon or signed-in clients subscribe to tables without RLS, and RLS tables need the service key on a server. For a private table like notes, you have two simple options:
- Call
refreshAll()from$app/navigationafter actions or on an interval, which reruns your load functions. - Stream a content-free "something changed" table and refetch through RLS, as shown in Build a realtime chat app with Postgres.
SvelteKit backend options compared
| WoWSQL | Supabase | Neon + your own auth | Self-hosted Postgres | |
|---|---|---|---|---|
| What you get | Postgres, auth, storage, realtime, auto REST | Postgres, auth, storage, realtime, auto REST | Serverless Postgres; Managed Better Auth listed on its plans | Only the database |
| SvelteKit SSR helper | None; wire cookies yourself as above | Official @supabase/ssr package with SvelteKit setup |
Depends on the auth library | Depends on your stack |
| Free tier | 1 project, 256 MB, 10,000 MAU | 2 projects, 500 MB, 50,000 MAU; pauses after ~1 week idle | 100 projects, 1 GB each, 100 CU-hours per project | Your server costs |
| Paid entry | Pro $25, Scale $99 | Pro from $25 plus usage | Launch, usage-based | Your server costs |
| Regions | Mumbai, US East, Frankfurt | 17 AWS regions, including Mumbai and London | AWS and Azure regions; none in India listed | Anywhere |
Sources read 29 November 2026: WoWSQL pricing, Supabase pricing, Supabase SSR client docs, Neon pricing, Supabase regions, Neon regions.
Where others are better: Supabase has an official cookie-based SSR helper with SvelteKit instructions and a bigger free tier, so you write less glue code. Neon gives you many more free projects and scales compute to zero. WoWSQL's case is one flat plan for database, auth, storage and realtime, regions in Mumbai, US East and Frankfurt, and the explicit server-side pattern above, which you fully control.
Launch checklist
- RLS on every table that holds user data, with a policy for each action you allow.
- Data API enabled and only the needed tables exposed.
WOWSQL_SERVICE_KEYset only in your host's server environment, never withpublic: true.- Cookies
httpOnly,secureandsameSite: 'lax'; CSRF protection left on. - Turnstile CAPTCHA enabled on sign-up before launch.
- A paid plan, or your own exports, before real data goes in: Free has no platform backups.
Related guides
- Vue backend with Postgres
- Next.js backend with Postgres
- Best backend for React apps
- How to add login to your app
- Build a realtime chat app with Postgres
- Supabase free tier limits in 2026
FAQ
What is the best backend for SvelteKit?
Any backend you can call from server load functions and form actions works. A Postgres BaaS such as WoWSQL or Supabase saves the most time, because auth, the database and a REST API come ready. Choose Supabase if you want its official SSR helper; choose WoWSQL for flat pricing and a Mumbai, US East or Frankfurt region.
How do I connect SvelteKit to a Postgres database?
Call the database from server-only code: +page.server.ts, +server.ts or modules under src/lib/server. With WoWSQL you call the REST API with the anon key and the user's JWT, so Row Level Security filters rows. With a raw Postgres driver, keep the connection string in $app/env/private.
Where should I store auth tokens in SvelteKit?
In httpOnly, secure, sameSite=lax cookies set by a form action or server route. Read them in hooks.server.ts, verify the user, and put it on event.locals. Avoid localStorage for access tokens in server-rendered apps.
How do I keep API keys secret in SvelteKit?
Define them without public: true in src/env.ts and import them from $app/env/private in server-only files. SvelteKit fails the build if browser code imports a server-only module. On SvelteKit 2, use $env/static/private.
Is there a Firebase alternative for Svelte apps?
Yes. Postgres backends such as WoWSQL and Supabase cover Firebase's main features (auth, database, storage, realtime) with SQL and Row Level Security instead of security rules. Firebase still leads for offline-first mobile sync.
Can I use Supabase-style RLS with SvelteKit form actions?
Yes. Send the signed-in user's JWT with each REST call from the action, and Postgres applies the policies. Use the service key only for admin tasks, because it bypasses RLS.
Create a free WoWSQL project · Auth docs · TypeScript SDK docs