The quickest backend for a Vue.js app is a backend as a service: your Vue code calls a hosted API for login, data and realtime, so you don't build or run a server. With WoWSQL you get PostgreSQL, auth, an auto-generated REST API and realtime from one SDK, @wowsql/sdk, which fits neatly into Vue 3 composables. This tutorial builds a Vite + Vue 3 + TypeScript todo app with sign-up, per-user data protected by Row Level Security, and a list that updates live, then covers Nuxt.
The code on this page was type-checked and built with vue-tsc and vite build against @wowsql/sdk 3.10.0, Vue 3.5.46 and Vite 8.3.8 on 26 November 2026.
Key facts
- SDK:
@wowsql/sdk3.10.0 on npm.ProjectAuthClienthandles sign-up, login and sessions (and accepts a custom tokenstorage);new WowSQLClient({ projectUrl, apiKey })gives.table()queries and.realtimechannels;WowSQLStoragehandles files (TypeScript SDK docs). Official SDKs also exist for Python, Go, Java, Kotlin, C#, PHP, Ruby, Rust, Swift and Flutter/Dart.- API: PostgREST at
https://<project>.wowsqlconnect.com/rest/v1. Send the anon key (wowsql_anon_…) inapikeyand the signed-in user's access token inAuthorization: Bearer …so RLS applies. The service key bypasses RLS and never belongs in a Vue app. There is no GraphQL API.- Realtime:
wss://<project>.wowsqlconnect.com/realtime/v1/websocket?apikey=…withINSERT,UPDATEandDELETEevents plus broadcast and presence. Enable a table first withPOST /realtime/v1/enable; payloads are capped at 64 KiB (realtime docs).- Auth: email and password, magic links, email or phone OTP, OAuth with 19 working providers, TOTP two-factor, optional Cloudflare Turnstile CAPTCHA (auth docs).
- Plans (pricing, 26 November 2026): Free $0 (1 project, 256 MB database, 512 MB files, 5 GB bandwidth, 10,000 MAU), Pro $25/month (100,000 MAU, daily backups kept 7 days), Scale $99/month. Regions: Mumbai, US East and Frankfurt.
Backend options for Vue
Vue renders the UI; the backend has to supply accounts, a database with access rules, file storage and an API. These hosted options all work from a Vue SPA without a server of your own:
| Data model | Free tier (checked 26 Nov 2026) | Paid from | Fits Vue when… | |
|---|---|---|---|---|
| WoWSQL | PostgreSQL + REST (PostgREST) | 1 project, 256 MB DB, 512 MB files, 10,000 MAU; read-only over a limit | Pro $25/month | You want SQL, RLS and a flat monthly price |
| Supabase | PostgreSQL + REST (PostgREST) | 2 projects, 500 MB DB, 1 GB files, 50,000 MAU; paused after 1 week idle | Pro from $25/month plus compute | You want the biggest Postgres BaaS ecosystem and a bigger free tier |
| Firebase | Firestore documents | Spark: 1 GiB, 50K reads/day, 20K writes/day, 50K auth MAU | Blaze, pay as you go | You need offline-first sync and Google's mobile tooling |
Sources: WoWSQL pricing, Supabase pricing, Firebase pricing. Supabase and Firebase both have larger free user allowances than WoWSQL. If Firebase's per-read billing worries you, see Firebase pricing explained.
What you will build
A Vue 3 single-page app where users sign up, sign in, see only their own todos, and watch the list update when a todo changes in another tab. Structure:
src/
lib/wowsql.ts # clients + a REST helper that sends the user's token
composables/useAuth.ts # shared, reactive auth state
composables/useTodos.ts # CRUD + realtime for one user's todos
components/LoginForm.vue
components/TodoList.vue
App.vue
No Pinia needed: a composable with module-level refs already shares state across components.
Step 1: Create the WoWSQL project and table
- Create a project at app.wowsql.com/signup in Mumbai, US East or Frankfurt.
- Enable Authentication for the project.
- Copy the project slug and the anon key (
wowsql_anon_…) from Settings → API. - In the SQL editor, create the table with RLS and one policy per operation:
create table public.todos (
id uuid primary key default gen_random_uuid(),
user_id uuid not null,
title text not null,
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 (auth.uid() = user_id);
create policy "insert own todos" on public.todos for insert with check (auth.uid() = user_id);
create policy "update own todos" on public.todos for update using (auth.uid() = user_id) with check (auth.uid() = user_id);
create policy "delete own todos" on public.todos for delete using (auth.uid() = user_id);
- Enable realtime for the table once:
curl -X POST 'https://myproject.wowsqlconnect.com/realtime/v1/enable' \
-H "apikey: wowsql_anon_your_key_here" \
-H "Content-Type: application/json" \
-d '{"schema_name":"public","table_name":"todos"}'
Without a select policy, an RLS-enabled table returns empty results to app users, so keep the first policy. More on policies in What is Row Level Security?
Step 2: Create the Vue app
npm create vite@latest my-todos -- --template vue-ts
cd my-todos
npm install
npm install @wowsql/sdk@3.10.0
Add .env.local (Vite exposes only variables prefixed VITE_, and everything it exposes ends up in the browser bundle, so the anon key is the only key that goes here):
VITE_WOWSQL_PROJECT=myproject
VITE_WOWSQL_ANON_KEY=wowsql_anon_your_key_here
When you build, Vite prints a note that fs and path were "externalized for browser compatibility". They come from the SDK's Node-only file-upload helper and don't affect the browser code here.
Step 3: The clients (src/lib/wowsql.ts)
import WowSQLClient, { ProjectAuthClient, type AuthTokenStorage } from '@wowsql/sdk'
const PROJECT = import.meta.env.VITE_WOWSQL_PROJECT // e.g. "myproject"
const ANON_KEY = import.meta.env.VITE_WOWSQL_ANON_KEY // wowsql_anon_...
const BASE = `https://${PROJECT}.wowsqlconnect.com`
// Keep tokens in sessionStorage so a page refresh doesn't sign the user out
const tokenStorage: AuthTokenStorage = {
getAccessToken: () => sessionStorage.getItem('wowsql_access'),
setAccessToken: (t) =>
t ? sessionStorage.setItem('wowsql_access', t) : sessionStorage.removeItem('wowsql_access'),
getRefreshToken: () => sessionStorage.getItem('wowsql_refresh'),
setRefreshToken: (t) =>
t ? sessionStorage.setItem('wowsql_refresh', t) : sessionStorage.removeItem('wowsql_refresh'),
}
// Auth: sign-up, sign-in, sessions
export const auth = new ProjectAuthClient({ projectUrl: PROJECT, apiKey: ANON_KEY, storage: tokenStorage })
// Data client: runs as the anon role (public data) and opens the realtime socket
export const db = new WowSQLClient({ projectUrl: PROJECT, apiKey: ANON_KEY })
// REST call as the signed-in user, so Row Level Security applies
export async function rest<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
const { accessToken } = auth.getSession()
const res = await fetch(`${BASE}/rest/v1/${path}`, {
...init,
headers: {
apikey: ANON_KEY,
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
...init.headers,
},
})
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
return (res.status === 204 ? null : await res.json()) as T
}
Two design choices worth knowing:
- Session storage adapter.
ProjectAuthClientaccepts any object withgetAccessToken,setAccessToken,getRefreshTokenandsetRefreshToken. Passing asessionStorageadapter means a page refresh keeps the user signed in, andlogout()clears it automatically. Swap in your own storage if your app has stricter rules. - Why
rest()instead ofdb.table()for user data. In 3.10.0,WowSQLClientsends the key you give it as bothapikeyand the bearer token, so its queries run as the anon role. That suits public tables. Per-user rows need the user's access token inAuthorization, which is whatrest()sends.
Step 4: Auth composable (src/composables/useAuth.ts)
import { ref, readonly } from 'vue'
import type { AuthUser } from '@wowsql/sdk'
import { auth } from '../lib/wowsql'
// Module-level state: every component that calls useAuth() shares one user
const user = ref<AuthUser | null>(null)
const error = ref('')
export function useAuth() {
async function restore() {
if (!auth.getSession().accessToken) return
try {
user.value = await auth.getUser() // GET /me with the stored token
} catch {
try {
await auth.refreshSession() // access token expired: try the refresh token once
user.value = await auth.getUser()
} catch {
auth.clearSession()
user.value = null
}
}
}
async function signIn(email: string, password: string, mode: 'login' | 'signup' = 'login') {
error.value = ''
try {
const res = mode === 'signup'
? await auth.signUp({ email, password })
: await auth.signIn({ email, password })
if (res.requires2fa) {
error.value = 'This account uses 2FA: add a TOTP step with verifyTwoFactorLogin().'
return
}
if (!res.session) {
error.value = 'Check your inbox to verify your email, then sign in.'
return
}
user.value = res.user ?? (await auth.getUser())
} catch (e) {
error.value = String(e)
}
}
async function signOut() {
try {
await auth.logout()
} finally {
user.value = null
}
}
return { user: readonly(user), error: readonly(error), restore, signIn, signOut }
}
Access tokens expire after the project's JWT expiry setting (24 hours by default), so restore() tries refreshSession() once before giving up. If you enable CAPTCHA in Attack Protection, pass captchaToken to signUp and signIn; for social login, see Add Google, GitHub and Apple login.
Step 5: Todos composable with realtime (src/composables/useTodos.ts)
import { ref, onMounted, onUnmounted } from 'vue'
import { db, rest } from '../lib/wowsql'
export type Todo = { id: string; title: string; done: boolean; user_id: string; created_at: string }
export function useTodos(userId: string) {
const todos = ref<Todo[]>([])
const loading = ref(false)
async function load() {
loading.value = true
try {
todos.value = await rest<Todo[]>('todos?select=*&order=created_at.desc')
} finally {
loading.value = false
}
}
async function add(title: string) {
await rest('todos', {
method: 'POST',
headers: { Prefer: 'return=representation' },
body: JSON.stringify({ title, user_id: userId }),
})
await load()
}
async function toggle(t: Todo) {
await rest(`todos?id=eq.${t.id}`, { method: 'PATCH', body: JSON.stringify({ done: !t.done }) })
await load()
}
async function remove(t: Todo) {
await rest(`todos?id=eq.${t.id}`, { method: 'DELETE' })
await load()
}
// Realtime: treat each event as "something changed" and re-read through REST,
// so RLS still decides which rows this user sees
const channel = db.realtime.channel(`todos-${userId}`)
onMounted(() => {
load()
channel.on('postgres_changes', { event: '*', schema: 'public', table: 'todos' }, () => load()).subscribe()
})
onUnmounted(() => {
channel.unsubscribe()
})
return { todos, loading, load, add, toggle, remove }
}
Why re-fetch instead of using the event payload? The realtime socket authenticates with the API key in the URL (browsers cannot set WebSocket headers), not with the user's token, and the SDK notes that anyone who can connect may listen on channels they join. Using the event as a "something changed" signal and re-reading through REST keeps RLS in charge. For genuinely public data, such as a shared chat room, you can render payload.new directly.
Step 6: Components
src/components/LoginForm.vue:
<script setup lang="ts">
import { ref } from 'vue'
import { useAuth } from '../composables/useAuth'
const { signIn, error } = useAuth()
const email = ref('')
const password = ref('')
</script>
<template>
<form @submit.prevent="signIn(email, password)">
<input v-model="email" type="email" placeholder="Email" required />
<input v-model="password" type="password" placeholder="Password" required />
<button type="submit">Sign in</button>
<button type="button" @click="signIn(email, password, 'signup')">Sign up</button>
<p v-if="error">{{ error }}</p>
</form>
</template>
src/components/TodoList.vue:
<script setup lang="ts">
import { ref } from 'vue'
import { useTodos } from '../composables/useTodos'
const props = defineProps<{ userId: string }>()
const { todos, loading, add, toggle, remove } = useTodos(props.userId)
const title = ref('')
async function submit() {
await add(title.value)
title.value = ''
}
</script>
<template>
<form @submit.prevent="submit">
<input v-model="title" placeholder="New todo" />
<button :disabled="!title">Add</button>
</form>
<p v-if="loading">Loading…</p>
<ul>
<li v-for="t in todos" :key="t.id">
<label><input type="checkbox" :checked="t.done" @change="toggle(t)" /> {{ t.title }}</label>
<button @click="remove(t)">Delete</button>
</li>
</ul>
</template>
src/App.vue:
<script setup lang="ts">
import { onMounted } from 'vue'
import { useAuth } from './composables/useAuth'
import LoginForm from './components/LoginForm.vue'
import TodoList from './components/TodoList.vue'
const { user, restore, signOut } = useAuth()
onMounted(restore)
</script>
<template>
<main v-if="user">
<p>Signed in as {{ user.email }} <button @click="signOut">Sign out</button></p>
<TodoList :key="user.id" :user-id="user.id" />
</main>
<LoginForm v-else />
</template>
The :key="user.id" on TodoList remounts the list (and its realtime subscription) if a different user signs in. Run npm run dev, sign up, add a todo, and open a second tab: changes appear in both.
Public data with the query builder
For tables the anon role may read, the SDK's query builder is shorter than rest():
const res = await db.table('announcements')
.select('*')
.order('created_at', 'desc')
.limit(5)
.get()
console.log(res.data)
Give that table a select policy that allows public reads, and keep writes behind user policies.
Using Nuxt
The same pieces work in Nuxt 3 or 4 with two rules: keep browser sessions on the client, and keep the service key on the server.
- Config. Put public values in
runtimeConfig.publicand the service key in private runtime config, which Nuxt never sends to the browser:
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
wowsqlServiceKey: '', // set NUXT_WOWSQL_SERVICE_KEY on the server only
public: {
wowsqlProject: '', // NUXT_PUBLIC_WOWSQL_PROJECT
wowsqlAnonKey: '', // NUXT_PUBLIC_WOWSQL_ANON_KEY
},
},
})
- Client-side auth and realtime. Create the clients in a client-only plugin (a file ending in
.client.tsunderplugins/), becausesessionStorageand WebSockets only exist in the browser. Read values withuseRuntimeConfig().publicinstead ofimport.meta.env, and render signed-in pages client-side, for example with<ClientOnly>. - Server routes for privileged work. Admin tasks, webhooks and reports that need the service key belong in
server/api/*.ts, where you can createnew WowSQLClient({ projectUrl, apiKey: useRuntimeConfig(event).wowsqlServiceKey }). Validate the caller's own access token first, because the service key bypasses RLS.
We built and type-checked the Vite version above; the Nuxt notes describe the pattern but were not built in this pass, so test them in your own app. The same server-and-client split is covered for Next.js in our Next.js Postgres backend guide.
Before you ship
- Run the RLS tests from our BaaS security checklist: signed out, then as two different users.
- Grep your
dist/folder forwowsql_service_to make sure no secret key was bundled. - Free projects have no platform backups; Pro and Scale keep daily backups for 7 days. Export your own copies either way.
- Pick the region closest to your users: Mumbai, US East or Frankfurt. Comparing a BaaS with running your own database? See AWS RDS in Mumbai vs a Postgres BaaS.
Related guides
- Best backend for React apps in 2026
- Next.js Postgres backend: App Router guide
- How to add login to your app without a backend
- Best realtime database for apps in 2026
- What is PostgREST?
- Open-source Firebase alternatives you can self-host
- Firebase pricing 2026: Spark vs Blaze, explained
FAQ
What is the best backend for a Vue.js app?
For most Vue apps, a backend as a service: Supabase or WoWSQL if you want PostgreSQL with Row Level Security and a REST API, or Firebase if you need offline-first document sync. WoWSQL adds a flat $0 / $25 / $99 monthly price and regions in Mumbai, US East and Frankfurt.
How do I connect Vue to a Postgres database?
Not directly from the browser. Use an API in front of Postgres: on WoWSQL, install @wowsql/sdk, sign users in with ProjectAuthClient, and call https://<project>.wowsqlconnect.com/rest/v1/<table> with the anon key in apikey and the user's access token in Authorization. RLS policies decide which rows each user can see.
Is there a Firebase alternative for Vue with SQL?
Yes. WoWSQL and Supabase both give a Vue app PostgreSQL, auth, file storage and realtime with an auto-generated REST API, so you query SQL tables instead of Firestore documents and protect them with Row Level Security instead of security rules.
How do I keep users logged in after a page refresh in Vue?
Persist the session. With @wowsql/sdk, pass a storage object (for example backed by sessionStorage) to ProjectAuthClient; on load, call getUser() and fall back to refreshSession() if the access token has expired.
Can I use WoWSQL with Nuxt?
Yes. Create the auth and realtime clients in a client-only plugin, put the anon key in runtimeConfig.public, and keep the service key in private runtime config used only by server routes. Validate the user's token in server routes before doing privileged work.
Do I need Pinia to manage auth state?
No. A composable that keeps the user in a module-level ref shares one reactive state across every component that calls it. Use Pinia if your app already does, or if you want devtools integration for the store.
Create a free WoWSQL project · Pricing · TypeScript SDK docs