tutorial··5 min read·WoWSQL Team

Nuxt 4 Backend with Postgres and Auth

Build a Nuxt 4 backend with Postgres and auth: Nitro server routes, httpOnly cookies, SSR-safe token refresh, Row Level Security and tested code samples.

A solid Nuxt 4 backend keeps every database call inside Nitro server routes (server/api), stores the user's session in httpOnly cookies set by the server, and lets Postgres Row Level Security decide which rows each user can read or change. WoWSQL gives you that backend without running a database or an auth server: Postgres, email and OAuth sign-in, and an auto-generated REST API, from $0 a month. This tutorial builds a todo app on Nuxt 4 with SSR data loading, a per-request auth client, token refresh that survives SSR, and a service key that never reaches the browser.

How we tested: every file below passed nuxi typecheck and nuxi build on Nuxt 4.7.1 (Nitro 2.14, h3 1.15) with @wowsql/sdk 3.10.0 on 2 December 2026. We ran the production server (.output/server/index.mjs) against a local stand-in for WoWSQL: a mock of the auth endpoints the SDK calls, with 8-second access tokens to force refreshes, 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

  • Nuxt runtime config: top-level runtimeConfig keys are server-only; anything under public is added to every page payload. Override values at runtime with NUXT_-prefixed variables (Nuxt runtime config, checked 2 Dec 2026).
  • SSR fetches forward cookies: when useFetch runs on the server, Nuxt uses useRequestFetch to pass the browser's headers and cookies to your API route (Nuxt data fetching, checked 2 Dec 2026). That matters for token refresh (Step 4).
  • WoWSQL REST: PostgREST at https://<project>.wowsqlconnect.com/rest/v1. Anon key (wowsql_anon_…) in apikey, 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 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

Browser ──$fetch / useFetch──> Nitro server routes (server/api/*)
   │                               │  server/middleware/auth.ts: cookie -> event.context.user
   │                               └── REST + user's JWT ──> WoWSQL Postgres (RLS)
   └── httpOnly cookies wowsql_access / wowsql_refresh (never readable by JS)
       service key: only in server runtimeConfig, only in admin routes

Why server routes instead of calling WoWSQL from Vue components:

  • No tokens in the browser. The Vue app only talks to /api/* on its own origin; cookies ride along automatically.
  • SSR pages arrive with data. useFetch('/api/todos') runs during server rendering and the result is sent to the client in the payload, so it isn't fetched twice.
  • One place for rules. Validation, rate limits and the service key live in server/, which Nuxt never bundles for the browser.

If you'd rather call WoWSQL straight from the browser with the anon key, that works too (RLS still applies); Vue backend with Postgres shows that client-side version.

Step 1: Create the project and table

Create a project at app.wowsql.com/signup in 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.todos (
  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),
  done boolean not null default false,
  created_at timestamptz not null default now()
);

alter table public.todos enable row level security;

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

grant select, insert, update, delete on public.todos to authenticated;

user_id defaults to auth.uid(), so the app never sends it. The update policy has both using and with check, so a user can't move a todo to someone else either. More in What is Row Level Security?.

Step 2: Create the app and runtime config

npx nuxi@latest init my-todos --template minimal
cd my-todos
npm install @wowsql/sdk@3.10.0
// nuxt.config.ts
export default defineNuxtConfig({
  compatibilityDate: '2025-07-15',
  runtimeConfig: {
    // Top-level keys are server-only. Override at runtime with NUXT_WOWSQL_URL, NUXT_WOWSQL_ANON_KEY, NUXT_WOWSQL_SERVICE_KEY.
    wowsqlUrl: '',        // https://myproject.wowsqlconnect.com
    wowsqlAnonKey: '',    // wowsql_anon_...
    wowsqlServiceKey: '', // wowsql_service_... bypasses RLS: never put it under `public`
  },
})
# .env (never commit this file)
NUXT_WOWSQL_URL=https://myproject.wowsqlconnect.com
NUXT_WOWSQL_ANON_KEY=wowsql_anon_your_key_here
NUXT_WOWSQL_SERVICE_KEY=wowsql_service_your_key_here

We keep even the URL and anon key out of public because only server routes call WoWSQL here. After a production build we searched .output/public and the rendered HTML: no key, no project URL.

Step 3: Server utilities and types

Files in server/utils are auto-imported into every server route and middleware:

// server/utils/wowsql.ts: auto-imported in server/ only, never bundled for the browser
import { ProjectAuthClient, WowSQLClient } from '@wowsql/sdk'
import type { H3Event } from 'h3'

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

// A new auth client per request: ProjectAuthClient remembers the last session in memory.
export function authClient(event: H3Event) {
  const { wowsqlUrl, wowsqlAnonKey } = useRuntimeConfig(event)
  return new ProjectAuthClient({ projectUrl: wowsqlUrl, apiKey: wowsqlAnonKey })
}

export function setAuthCookies(event: H3Event, s: { accessToken: string; refreshToken: string }) {
  setCookie(event, 'wowsql_access', s.accessToken, cookieOpts)
  setCookie(event, 'wowsql_refresh', s.refreshToken, cookieOpts)
}

export function clearAuthCookies(event: H3Event) {
  deleteCookie(event, 'wowsql_access', { path: '/' })
  deleteCookie(event, '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>(event: H3Event, path: string, init: { method?: string; body?: unknown; headers?: Record<string, string> } = {}): Promise<T> {
  const token = event.context.accessToken
  if (!token) throw createError({ statusCode: 401, statusMessage: 'Sign in first' })
  const { wowsqlUrl, wowsqlAnonKey } = useRuntimeConfig(event)
  const res = await fetch(`${wowsqlUrl}/rest/v1/${path}`, {
    method: init.method ?? 'GET',
    headers: { apikey: wowsqlAnonKey, Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...init.headers },
    body: init.body === undefined ? undefined : JSON.stringify(init.body),
  })
  const text = await res.text()
  if (!res.ok) throw createError({ statusCode: res.status, statusMessage: `WoWSQL: ${text}` })
  return (text ? JSON.parse(text) : null) as T
}

// Service key client: bypasses RLS. Admin jobs only.
export function adminDb(event: H3Event) {
  const { wowsqlUrl, wowsqlServiceKey } = useRuntimeConfig(event)
  if (!wowsqlServiceKey) throw createError({ statusCode: 500, statusMessage: 'Service key not configured' })
  return new WowSQLClient({ projectUrl: wowsqlUrl, apiKey: wowsqlServiceKey })
}
// server/types.d.ts
import type { AuthUser } from '@wowsql/sdk'

declare module 'h3' {
  interface H3EventContext {
    user: AuthUser | null
    accessToken: string | null
  }
}
export {}

Notes:

  • One ProjectAuthClient per request. In SDK 3.10.0 the client remembers the last session in memory, and getUser() without a token falls back to it. Sharing one instance across a Nitro server could answer one user's request with another user's session.
  • Name clash we hit: h3 already auto-imports a clearSession helper (for its own sealed sessions), and Nuxt warned about the duplicate. We named ours setAuthCookies and clearAuthCookies.

Step 4: Server middleware: session, refresh and the SSR trap

// server/middleware/auth.ts: runs before every page render and API route
export default defineEventHandler(async (event) => {
  event.context.user = null
  event.context.accessToken = null

  const access = getCookie(event, 'wowsql_access')
  const refresh = getCookie(event, 'wowsql_refresh')
  if (!access && !refresh) return

  const auth = authClient(event)
  if (access) {
    try {
      event.context.user = await auth.getUser(access) // GET /api/auth/me
      event.context.accessToken = access
      return
    } catch {
      // expired or revoked: try the refresh token
    }
  }
  if (!refresh) return

  try {
    const { session } = await auth.refreshSession(refresh)
    if (!session) return
    setAuthCookies(event, session)
    event.context.user = await auth.getUser(session.accessToken)
    event.context.accessToken = session.accessToken
    // SSR data calls (useFetch to /api/...) copy this request's cookie header.
    // Swap in the new tokens so they don't try to refresh again with the old ones.
    const others = (getRequestHeader(event, 'cookie') ?? '')
      .split(';').map((c) => c.trim()).filter((c) => c && !c.startsWith('wowsql_'))
    event.node.req.headers.cookie = [...others, `wowsql_access=${session.accessToken}`, `wowsql_refresh=${session.refreshToken}`].join('; ')
  } catch {
    clearAuthCookies(event)
  }
})

The last block fixes a trap we reproduced. When a page renders on the server, Nitro runs this middleware for the page request, then useFetch('/api/todos') makes an internal request that copies the original cookie header. If the access token had expired, the page request refreshes it, but the internal request still carries the old tokens and refreshes again. Without the swap, our test made two refresh calls; the second one used a refresh token the first had already replaced in our mock, so the user was bounced to /login. With the swap there was exactly one refresh, the page rendered signed in, and the browser received two new Set-Cookie headers. Whether WoWSQL rotates refresh tokens on every use isn't stated in its auth docs, so code as if it does.

Step 5: Auth routes

// server/api/auth/login.post.ts: sign in or sign up, then set httpOnly cookies
export default defineEventHandler(async (event) => {
  const { email, password, mode } = await readBody<{ email?: string; password?: string; mode?: string }>(event)
  if (!email || !password || password.length < 8) {
    throw createError({ statusCode: 400, statusMessage: 'Email and an 8+ character password are required.' })
  }
  const auth = authClient(event)
  try {
    const res = mode === 'signup' ? await auth.signUp({ email, password }) : await auth.signIn({ email, password })
    if (res.requires2fa) return { ok: false, reason: '2fa' as const }
    if (!res.session) return { ok: false, reason: 'verify-email' as const }
    setAuthCookies(event, res.session)
    return { ok: true, reason: null }
  } catch (e) {
    throw createError({ statusCode: 400, statusMessage: e instanceof Error ? e.message : 'Sign-in failed' })
  }
})
// server/api/auth/logout.post.ts
export default defineEventHandler(async (event) => {
  if (event.context.accessToken) await authClient(event).logout(event.context.accessToken).catch(() => {})
  clearAuthCookies(event)
  return { ok: true }
})
// server/api/auth/me.get.ts: what the browser is allowed to know about the session
export default defineEventHandler((event) => {
  const user = event.context.user
  return user ? { id: user.id, email: user.email } : null
})

/api/auth/me returns only the fields the UI needs, never the tokens. For Google or GitHub sign-in, follow Add social login with OAuth and call setAuthCookies in a server/routes/auth/callback.get.ts handler.

Step 6: Todo routes, scoped by RLS

// server/api/todos/index.get.ts
type Todo = { id: string; title: string; done: boolean; created_at: string }

export default defineEventHandler((event) =>
  // RLS returns only this user's rows: no user_id filter needed, and none can be forged
  rest<Todo[]>(event, 'todos?select=id,title,done,created_at&order=created_at.desc&limit=100'),
)
// server/api/todos/index.post.ts
export default defineEventHandler(async (event) => {
  const { title } = await readBody<{ title?: string }>(event)
  const clean = String(title ?? '').trim()
  if (!clean || clean.length > 200) throw createError({ statusCode: 400, statusMessage: 'Title must be 1-200 characters.' })
  // user_id defaults to auth.uid() in the table, so we never send it
  const [todo] = await rest<unknown[]>(event, 'todos', { method: 'POST', body: { title: clean }, headers: { Prefer: 'return=representation' } })
  return todo
})
// server/api/todos/[id].patch.ts
export default defineEventHandler(async (event) => {
  const id = encodeURIComponent(getRouterParam(event, 'id') ?? '')
  const { done } = await readBody<{ done?: boolean }>(event)
  // If the row isn't yours, RLS matches zero rows and nothing changes
  const rows = await rest<unknown[]>(event, `todos?id=eq.${id}`, { method: 'PATCH', body: { done: Boolean(done) }, headers: { Prefer: 'return=representation' } })
  if (!rows.length) throw createError({ statusCode: 404, statusMessage: 'Not found' })
  return rows[0]
})
// server/api/todos/[id].delete.ts
export default defineEventHandler(async (event) => {
  const id = encodeURIComponent(getRouterParam(event, 'id') ?? '')
  await rest(event, `todos?id=eq.${id}`, { method: 'DELETE' })
  return { ok: true }
})

In our test, a second user's GET /api/todos returned [], and their PATCH on the first user's todo returned 404, because RLS made the row invisible and the update matched nothing. The owner's PATCH returned the updated row.

Step 7: Pages and a route guard

// app/middleware/auth.global.ts: send signed-out visitors to /login
export default defineNuxtRouteMiddleware(async (to) => {
  if (to.path === '/login') return
  const user = useState<{ id: string; email: string } | null>('user', () => null)
  if (!user.value) user.value = await useRequestFetch()('/api/auth/me')
  if (!user.value) return navigateTo('/login')
})
<!-- app/pages/login.vue -->
<script setup lang="ts">
const email = ref('')
const password = ref('')
const error = ref('')

async function submit(mode: 'login' | 'signup') {
  error.value = ''
  try {
    const res = await $fetch('/api/auth/login', { method: 'POST', body: { email: email.value, password: password.value, mode } })
    if (!res.ok) { error.value = res.reason === 'verify-email' ? 'Check your inbox, then sign in.' : 'Add a 2FA step first.'; return }
    useState('user').value = null // re-read the session on the next navigation
    await navigateTo('/')
  } catch (e: any) {
    error.value = e?.statusMessage ?? 'Sign-in failed'
  }
}
</script>

<template>
  <form @submit.prevent="submit('login')">
    <input v-model="email" type="email" placeholder="you@example.com" required>
    <input v-model="password" type="password" minlength="8" required>
    <button>Sign in</button>
    <button type="button" @click="submit('signup')">Create account</button>
    <p v-if="error" role="alert">{{ error }}</p>
  </form>
</template>
<!-- app/pages/index.vue -->
<script setup lang="ts">
const user = useState<{ id: string; email: string } | null>('user')
// During SSR, useFetch calls the server route directly and forwards the browser's cookies
const { data: todos, refresh } = await useFetch('/api/todos', { default: () => [] })
const title = ref('')

async function add() {
  await $fetch('/api/todos', { method: 'POST', body: { title: title.value } })
  title.value = ''
  await refresh()
}
async function toggle(id: string, done: boolean) {
  await $fetch(`/api/todos/${id}`, { method: 'PATCH', body: { done } })
  await refresh()
}
async function remove(id: string) {
  await $fetch(`/api/todos/${id}`, { method: 'DELETE' })
  await refresh()
}
async function logout() {
  await $fetch('/api/auth/logout', { method: 'POST' })
  user.value = null
  await navigateTo('/login')
}
</script>

<template>
  <main>
    <p>Signed in as {{ user?.email }} <button @click="logout">Sign out</button></p>
    <form @submit.prevent="add">
      <input v-model="title" maxlength="200" required>
      <button>Add</button>
    </form>
    <ul>
      <li v-for="t in todos" :key="t.id">
        <input type="checkbox" :checked="t.done" @change="toggle(t.id, !t.done)">
        {{ t.title }}
        <button @click="remove(t.id)">Delete</button>
      </li>
    </ul>
  </main>
</template>

useRequestFetch() in the route middleware forwards the browser's cookies during SSR, and after hydration it behaves like $fetch. An anonymous visit to / returned a 302 to /login; a signed-in visit rendered the todo list in the initial HTML.

Step 8: Admin work with the service key

// server/api/admin/stats.get.ts
const ADMINS = new Set(['you@yourcompany.com'])

export default defineEventHandler(async (event) => {
  const user = event.context.user
  if (!user || !ADMINS.has(user.email)) throw createError({ statusCode: 403, statusMessage: 'Admins only' })
  // Service key: counts every user's todos, ignoring RLS. Only the number leaves the server.
  return { total: await adminDb(event).table('todos').count() }
})

Never use adminDb to load a normal user's data "and filter it in code": one forgotten filter leaks every row. For live updates on private tables, see Build a realtime chat app with Postgres: WoWSQL Realtime can't filter change events by RLS, so stream a content-free events table and refetch through your routes.

Nuxt backend options compared

WoWSQL (this guide) Supabase + @nuxtjs/supabase Your own Postgres + an auth library
Nuxt integration None; the server code above @nuxtjs/supabase module (2.1.0 on npm) with composables and server helpers Depends on the library
Session handling httpOnly cookies you set in server routes SSR cookies via @supabase/ssr (useSsrCookies, on by default) Your choice
Server helpers event.context.user from your middleware serverSupabaseUser, serverSupabaseClient, serverSupabaseServiceRole Your choice
Route protection Your route middleware Built-in redirect options (login, callback, include, exclude) Your code
Free tier 1 project, 256 MB, 10,000 MAU 2 projects, 500 MB, 50,000 MAU; paused after 1 week of inactivity Your server costs
Regions Mumbai, US East, Frankfurt Many AWS regions Anywhere

Sources checked 2 Dec 2026: Nuxt Supabase module, module options, serverSupabaseUser, Supabase pricing, WoWSQL pricing.

Where others are better: the Nuxt Supabase module gives you composables, server helpers and automatic redirects out of the box, so you write far less code than this guide, and Supabase's free tier is larger. WoWSQL has no Nuxt module today; you trade those helpers for a backend you control line by line, one flat price that includes auth, storage and realtime, and regions in Mumbai, US East and Frankfurt.

Related guides

FAQ

What is the best backend for Nuxt 4?

One that lets Nitro server routes do the data work with the user's own token, so database rules apply on the server. Supabase with @nuxtjs/supabase is the most turnkey; WoWSQL works with a little server code and flat pricing; your own Postgres plus an auth library gives full control.

How do I connect Nuxt to Postgres?

Either call a Postgres REST API (such as WoWSQL's PostgREST endpoint) from server/api routes with fetch, or use a Postgres driver in those routes if your host keeps long-lived connections. Keep credentials in server-only runtimeConfig.

How do I add authentication to Nuxt 4 without a module?

Sign users in from a server/api/auth/login.post.ts route, store the access and refresh tokens in httpOnly cookies with h3's setCookie, read them in server/middleware, and put the user on event.context. Guard pages with a global route middleware that calls /api/auth/me.

Why does my Nuxt app log users out after the access token expires?

During SSR, useFetch to your own API copies the original cookie header. If the page request refreshed the token, the inner request still has the old one and may refresh again with a used refresh token. Update the request's cookie header after refreshing, as in Step 4.

Is runtimeConfig safe for secrets in Nuxt?

Top-level runtimeConfig keys are server-only. Anything under runtimeConfig.public is sent to the browser in the page payload, so never put a service key there.

What is a good Supabase alternative for Nuxt?

WoWSQL offers the same building blocks (Postgres, auth, auto REST, realtime) with Mumbai, US East and Frankfurt regions and plans at $0, $25 and $99 a month. It has no Nuxt module, so you write the server routes shown here.

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