Why PocketBase Fits Modern Next.js Stacks
PocketBase delivers a complete backend in a single 15 MB Go binary that includes SQLite storage, authentication, realtime subscriptions via Server-Sent Events, file storage with automatic thumbnails, an admin UI, and an embedded reverse proxy. Version 0.22 adds improved migration tooling, expanded OAuth providers, and better collection rule expressions.
For startups and small teams this means eliminating the need for separate Supabase, Firebase or Appwrite accounts while retaining full data ownership. You run the binary on a $5 VPS, Docker, or even inside a Cloudflare Tunnel for zero-egress development. The JavaScript SDK works seamlessly with Next.js App Router, Server Actions and React Server Components.
Trade-offs exist. SQLite handles 50-100 concurrent writes comfortably before you switch to PostgreSQL mode. You must handle backups, updates and scaling yourself. However, for most SaaS products under 10k monthly active users the operational burden stays lower than orchestrating Prisma, Redis and separate auth services.
Local Setup and Project Structure
Download the latest pocketbase_0.22.0_linux_amd64.zip from the official GitHub releases, extract the binary and place it in your project root. Create a pocketbase directory alongside your Next.js app to keep data isolated.
mkdir pb && cd pb
wget https://github.com/pocketbase/pocketbase/releases/download/v0.22.0/pocketbase_0.22.0_linux_amd64.zip
unzip pocketbase_0.22.0_linux_amd64.zip
./pocketbase serve
The admin UI becomes available at http://127.0.0.1:8090/_/. Create your first admin account through the UI. In a monorepo using Turborepo you can add a package.json script "pb": "cd ../pb && ./pocketbase serve" so turbo run pb starts both services.
Next.js lives in its own directory using the App Router. Install the official SDK:
npm install pocketbase@0.21.0
Create a singleton client factory that reuses the instance across Server Components while attaching the correct auth cookie on the client.
Collection Design and Access Rules
PocketBase uses collections instead of tables. For a prompt library SaaS you might create four collections: users, prompts, categories and prompt_likes. Each collection receives API rules written in a JavaScript-like expression language.
Example rule for the prompts collection that allows public reads but restricts writes to the record owner:
@request.auth.id != "" && (
@request.auth.id = user ||
@request.data.public = true
)
Relation fields are created through the admin UI by selecting the target collection and choosing one-to-one or one-to-many. In 0.22 the expanded rule editor shows real-time validation and autocomplete for fields. Use the created and updated system fields for audit trails without extra columns.
After defining collections, export the schema as JSON or use PocketBase migrations. The migrate create command generates a timestamped Go file you can commit, allowing reproducible environments across developers and CI.
Authentication Flow with Server Actions
Auth is token-based with secure HTTP-only cookies. The following Server Action handles login and sets the cookie for subsequent requests.
'use server';
import PocketBase from 'pocketbase';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
export async function login(email: string, password: string) {
const pb = new PocketBase('http://127.0.0.1:8090');
const authData = await pb.collection('users').authWithPassword(email, password);
const cookieStore = cookies();
cookieStore.set('pb_auth', pb.authStore.exportToCookie(), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 7,
});
redirect('/dashboard');
}
On the client you can call this action from a form. For middleware protection create a middleware.ts that reads the cookie, refreshes the auth state if needed, and redirects unauthenticated users. Refresh logic uses pb.authStore.loadFromCookie(cookie) followed by await pb.collection('users').authRefresh() inside a try/catch.
OAuth flows follow the same pattern using authWithOAuth2Code. PocketBase 0.22 ships with improved state and PKCE handling, reducing the attack surface for callback URL manipulation.
Data Fetching in Server Components
Server Components can query PocketBase directly because they run on the server. The SDK automatically includes the auth cookie when you pass the request headers.
import PocketBase from 'pocketbase';
import { cookies } from 'next/headers';
async function getPrompts() {
const cookieStore = cookies();
const pb = new PocketBase('http://127.0.0.1:8090');
pb.authStore.loadFromCookie(cookieStore.get('pb_auth')?.value || '');
const records = await pb.collection('prompts').getList(1, 20, {
sort: '-created',
expand: 'category,user',
filter: 'public = true',
});
return records;
}
export default async function PromptGrid() {
const { items } = await getPrompts();
return (
<ul>
{items.map((prompt) => (
<li key={prompt.id}>{prompt.title}</li>
))}
</ul>
);
}
Because Server Components are static by default, wrap dynamic queries with export const dynamic = 'force-dynamic' or use the revalidatePath API after mutations. For cached but periodically refreshed data, combine PocketBase with Next.js unstable_cache.
Realtime Subscriptions in React Client Components
Realtime uses Server-Sent Events under the hood. The SDK abstracts this into a subscribe method that works in client components. Create a custom hook:
'use client';
import { useEffect, useState } from 'react';
import PocketBase from 'pocketbase';
export function useRealtimeCollection(collection: string, filter = '') {
const [records, setRecords] = useState([]);
const pb = new PocketBase('http://127.0.0.1:8090');
useEffect(() => {
const unsubscribe = pb.collection(collection).subscribe('*', (e) => {
if (e.action === 'create') setRecords(prev => [...prev, e.record]);
if (e.action === 'update') setRecords(prev => prev.map(r => r.id === e.record.id ? e.record : r));
if (e.action === 'delete') setRecords(prev => prev.filter(r => r.id !== e.record.id));
}, { filter });
return () => unsubscribe();
}, [collection, filter]);
return records;
}
This hook updates UI instantly when another user adds a prompt. Because subscriptions survive page transitions when using the App Router layout, place the subscription at a high level in the component tree for dashboards. Monitor memory usage; each active subscription consumes a goroutine on the PocketBase side. Version 0.22 improved connection limits and includes a built-in dashboard metric for active subscriptions.
File Storage and Resumable Uploads
PocketBase serves files from /api/files/<collection>/<recordId>/<filename> and automatically creates 300×300 and 100×100 thumbnails when you enable the option on a file field. For large uploads integrate with the TUS protocol or use the SDK's upload method with progress callbacks.
const formData = new FormData();
formData.append('file', selectedFile);
const record = await pb.collection('prompts').create({
title: 'New prompt',
file: formData,
});
On the admin side you can restrict file types and maximum size per collection. When deploying behind a CDN, configure PocketBase to return proper cache-control headers by setting --https and letting Caddy handle TLS termination and caching.
Extending Logic with Hooks and Custom Routes
PocketBase allows Go hooks that run before or after CRUD operations. Create a pb_hooks/main.pb.js file (PocketBase 0.22 supports JavaScript hooks via an embedded interpreter). Example hook that runs after a prompt is created to generate embeddings using an external Ollama service:
onRecordAfterCreateRequest((e) => {
if (e.collection.name === "prompts") {
const promptText = e.record.get("text");
$http.send({
url: "http://localhost:11434/api/embeddings",
method: "POST",
body: JSON.stringify({
model: "nomic-embed-text",
prompt: promptText
}),
headers: { "Content-Type": "application/json" }
}).then(res => {
const embedding = JSON.parse(res.raw).embedding;
$app.dao().db().newQuery("UPDATE prompts SET embedding = {:embedding} WHERE id = {:id}")
.bind({ embedding: JSON.stringify(embedding), id: e.record.id })
.execute();
});
}
});
For more complex endpoints add custom routes in the same hooks file using $app.onServe or compile a custom Go binary. This approach keeps the surface area small compared to maintaining a separate NestJS or Hono service.
Production Deployment with Docker and PostgreSQL
The official Docker image makes deployment straightforward. Create a Dockerfile that copies your binary, migrations and hooks:
FROM alpine:latest
RUN apk add --no-cache ca-certificates
COPY pocketbase /usr/local/bin/
COPY pb_migrations /pb_migrations
COPY pb_hooks /pb_hooks
EXPOSE 8090
CMD ["pocketbase", "serve", "--http=0.0.0.0:8090"]
Switch from SQLite to PostgreSQL by passing --dir=/pb_data and configuring the connection string in the admin UI under Settings → Database. For high availability run multiple replicas behind a load balancer; each replica connects to the same Postgres instance. Use Litestream to continuously back up the SQLite directory to S3 if you stay with the embedded database.
Health checks should call the /api/health endpoint which returns {"code":200,"data":{}}. Combine this with a simple Caddyfile for automatic HTTPS:
yourdomain.com {
reverse_proxy localhost:8090
}
Security Model and Hardening Steps
Collection rules form the primary authorization layer. Never rely on client-side filtering. Always set explicit list and view rules. In 0.22 you can reference @request.headers and @request.query inside rules, enabling header-based tenant isolation for multi-tenant SaaS.
Additional hardening steps include:
- Enable rate limiting in the settings panel (default 100 requests per 60 seconds per IP).
- Run PocketBase behind a WAF or Cloudflare proxy.
- Use automated backups with
pocketbase backup createscheduled via cron. - Audit logs are stored in a separate collection; create an
audit_logscollection and a hook that records every admin action. - Rotate the admin password and never expose the
_admin route publicly.
Compared to rolling your own auth with Lucia, PocketBase reduces the attack surface because the auth implementation is battle-tested in production by thousands of hobby and commercial projects.
Performance Characteristics and Scaling Limits
Single binary PocketBase with SQLite routinely serves several thousand requests per second on a modest VPS when most traffic is reads. Write-heavy workloads benefit from connection pooling when switched to PostgreSQL. The realtime SSE implementation uses a pub/sub pattern that scales linearly until you reach several hundred concurrent subscribers per collection.
Common scaling path: start with SQLite on a $6 DigitalOcean droplet, add Redis for caching frequent queries inside Next.js, then migrate the primary database to managed PostgreSQL when write QPS exceeds 30. Because the REST API is identical, the frontend code requires zero changes during migration.
Benchmark your own workload. A simple autocannon -c 100 -d 30 http://localhost:8090/api/collections/prompts/records command gives realistic numbers for your hardware and query complexity.
Case Study: AI Prompt Marketplace Built in One Weekend
A weekend project used PocketBase to power promptbase.dev, a marketplace where users sell and discover LLM prompts. Collections were:
- users with OAuth via GitHub and email/password
- prompts containing title, text, tags (array field), price, embedding vector
- purchases linking buyer, prompt and Stripe session ID
Next.js Server Actions handled purchase flows that called Stripe then created a purchase record. Realtime subscription on the prompts collection updated the trending list without page refreshes. File storage kept prompt preview images with automatic optimization.
Search used PocketBase filter expressions on tags combined with a simple client-side fuse.js fallback. When vector search became necessary the embedding field was indexed via a custom hook that called a local Ollama instance. The entire backend, including admin UI for content moderation, required less than 120 lines of Go/JavaScript hook code.
Deployment used Docker on Fly.io with a persistent volume for SQLite and automated daily backups to Backblaze B2. Monthly cost stayed under $12 even at 800 active users. The same stack now powers three other internal tools with zero additional infrastructure.
Migration Strategies from Firebase or Supabase
Export Firebase collections to JSON then import via the PocketBase admin UI or a small script using the SDK batch methods. Map Firebase Authentication UIDs to PocketBase user records by storing the original UID in a custom field and adjusting rules accordingly.
Supabase users benefit from the similar PostgreSQL foundation. The PocketBase CLI can import a Postgres dump directly. Realtime subscriptions map almost one-to-one; replace Supabase channel subscriptions with PocketBase subscribe calls. Edge Functions become PocketBase hooks, removing cold-start latency.
Data consistency during migration is achieved by running both systems in parallel for one week, syncing writes with a small Node script listening to PocketBase webhooks and forwarding them to the legacy provider until traffic is fully cut over.
Maintenance and Monitoring
Enable PocketBase logs with --log=true and pipe output to a file or Loki instance. The built-in metrics endpoint at /api/metrics exposes Prometheus-compatible counters for requests, errors and active realtime connections. Set up a simple Grafana dashboard that alerts when error rate exceeds 0.5% or when disk usage on the data directory passes 80%.
Update strategy: download the new binary, replace the old one, run any pending migrations with ./pocketbase migrate up, then restart. Because state lives in the data directory, downtime is typically under 10 seconds.
For teams larger than three developers, store collection schemas in code using the official migration system instead of the admin UI to prevent drift between environments.
PocketBase 0.22 represents a sweet spot between the simplicity of a Firebase-style backend and the control of a self-hosted solution. When combined with Next.js 15's streaming, partial prerendering and React Compiler, the resulting applications ship fast, stay secure by default, and incur minimal cloud spend. The patterns shown here have powered multiple production SaaS products without requiring dedicated backend engineers. Start with the single binary, measure your actual traffic patterns, and only add complexity when real bottlenecks appear.
