Mastering PocketBase: A Comprehensive Guide to Using This Open‑Source Backend for Your Web and Mobile Apps

Building a modern application often requires a robust backend to handle data persistence, user authentication, file storage, and real‑time features. While solutions like Firebase and Supabase are popular, they can introduce vendor lock‑in, recurring costs, or complex configuration. PocketBase emerges as a refreshing alternative: a single, self‑hosted executable that bundles an embedded SQLite database, an admin UI, a RESTful API, and real‑time subscriptions into one neat package. Written in Go and released under an MIT license, PocketBase is lightweight (around 30 MB), blazingly fast, and remarkably easy to set up. Whether you are building a prototype, a side project, or a production application, PocketBase gives you complete control over your data without sacrificing developer experience. In this comprehensive tutorial, we will walk through everything you need to know to use PocketBase as your backend, from installation and schema design to authentication, file uploads, real‑time updates, and deployment best practices.

PocketBase’s architecture is elegantly simple. It runs as a single binary – you download it, run it, and instantly get an admin panel at http://localhost:8090/_/. Under the hood, it stores all records in an SQLite database file named pb_data, but you never write raw SQL. Instead, you interact with “collections” (similar to tables) through a clean REST API. Each collection can have fields of various types: text, number, boolean, date, relation, file, and more. The admin UI lets you define these fields visually, set API rules, manage users, and browse data – all without writing a single line of server code. For frontend integration, PocketBase provides official JavaScript SDKs (for web and React Native) and community SDKs for Dart, Python, Swift, and others. The SDKs handle API calls, token refresh, and real‑time subscriptions, so you can focus on building your UI. In the following sections, we will set up PocketBase locally, create a sample app (a simple task manager with users and attachments), and explore every aspect of the backend that matters to developers.

Article illustration

Step 1: Installing and Running PocketBase

The first step is to download the correct binary for your operating system from the official PocketBase releases page. You can choose from pre‑compiled versions for Windows, macOS, Linux, and even ARM architectures like Raspberry Pi. Once downloaded, extract the executable – it is a single file with no dependencies. For example, on a Mac, you typically get a file called pocketbase after unzipping. Move it to a directory where you want to store your project (e.g., ~/myapp/pocketbase). Open a terminal in that directory and run:

./pocketbase serve

On Windows, use pocketbase.exe serve. The server will start on port 8090 by default. You will see logs indicating that PocketBase is listening and that the admin UI is available at http://127.0.0.1:8090/_/. Open that URL in your browser – you will be greeted by a registration form. Create your first admin account (email and password). After registering, you will see the admin dashboard, which contains a sidebar with “Collections”, “API Rules”, “Settings”, and a “Logs” section. This dashboard is your control center. Take a moment to explore the default collections: PocketBase creates a built‑in “users” collection for authentication, and a “superusers” collection for admin accounts. You can extend the users collection with custom fields later. For now, we have a fully working backend with a SQLite database, all running locally with zero configuration.

One important note: by default, PocketBase stores its data inside a folder named pb_data located in the same directory as the executable. You can change this by passing the --dir flag: ./pocketbase serve --dir=/path/to/data. It is also possible to enable HTTPS with a Let’s Encrypt certificate, but for development, HTTP on localhost is fine. To stop the server, press Ctrl+C. If you want to run it in the background, you can use tools like pm2 or a screen session. For production, we will talk about deployment later. But for now, your local PocketBase instance is ready to be populated with data.

Step 2: Creating Your First Collection – A Task Manager Schema

Let’s build a simple task management application. We need a collection to store tasks with fields like title, description, due date, status, and an optional file attachment. In the PocketBase admin UI, click on “Collections” in the left sidebar, then click the “New collection” button. Give your collection a name – I will use “tasks” (PocketBase automatically pluralizes it for the API endpoint as /api/collections/tasks/records). The “System collection” toggle should be off (unless you are building a system extension). Now let’s define the fields:

Field Name Type Options / Constraints
title Text Required, Max 200 chars
description Editor (rich text) Optional
due_date Date Required
status Select Options: pending, in_progress, completed; default: pending
attachment File Max size 5MB, allowed types: image/jpeg, image/png, application/pdf
user Relation Relation to users collection, single record

After adding these fields, save the collection. PocketBase automatically generates an ID field, a created timestamp, and an updated timestamp – you do not need to add them. Now go to the “API Rules” section (under the collection settings) to configure who can read, create, update, and delete tasks. For now, let’s keep it open for authenticated users only: set “List/Search”, “View”, “Create”, “Update”, “Delete” to @request.auth.id != "" (which checks that the requesting user is logged in). Later we can refine with role‑based rules. You can also set defaults like the user field to automatically take the authenticated user’s ID using the placeholder @request.auth.id. PocketBase gives you an expressive rule language – this is one of its most powerful features. After saving the rules, you can test the API directly from the admin UI using the “API preview” tab or through cURL. For example, to list all tasks: http://localhost:8090/api/collections/tasks/records (but you will get a 403 error if not authenticated). This brings us to the next step: authentication.

Step 3: Setting Up User Authentication and Permissions

PocketBase comes with a built‑in user authentication system. The default “users” collection already has fields for email, password (hashed), and optional avatar. You can extend it by adding custom fields (like full name or profile bio) in the admin UI under the “users” collection. To register a new user, your frontend sends a POST request to /api/collections/users/records with email, password, and passwordConfirm. The response includes a token (a JWT) and the user record. Similarly, authentication (login) is done via /api/collections/users/auth-with-password with identity (email) and password. The returned token must be stored on the client (e.g., in localStorage or an HTTP‑only cookie) and sent in the Authorization: Bearer <token> header for subsequent requests. The official SDKs handle all this automatically, but understanding the raw API is important for debugging.

In the admin UI, go to “Collections” -> “users” -> “API Rules”. You will see that the default rules already allow any user to create a new user (registration). The @request.auth.id != "" rule on other operations ensures that only authenticated users can view/update their own record. You can customize the rule to, for example, allow admin superusers to list all users. PocketBase’s rule engine supports @request.auth, @request.data, @collection, and even relational checks (e.g., user.id = @request.auth.id). For the tasks collection we created, we already set the List/Search rule to authenticated users – but every authenticated user can see all tasks. To restrict visibility to tasks owned by the user, change the rule to: user.id = @request.auth.id. That way, a user only sees their own tasks. Similarly, for Create, you can set default value for user field to @request.auth.id in the collection schema, and set the rule to allow creation only if user.id = @request.auth.id. PocketBase’s permission system is flexible yet simple – you can enforce row‑level security without writing any server logic.

Step 4: Using the PocketBase JavaScript SDK to Perform CRUD Operations

Now that our collections and authentication are ready, let’s integrate PocketBase into a frontend app. We’ll use the official JavaScript SDK (available on npm as pocketbase). Installation is straightforward: npm install pocketbase. Then import it into your project:

import PocketBase from 'pocketbase';
const pb = new PocketBase('http://127.0.0.1:8090');

For authentication, you can call pb.collection('users').authWithPassword(email, password). This stores the token internally in pb.authStore and automatically attaches it to future requests. Registration is pb.collection('users').create({...}). After login, you can perform CRUD on tasks. For example, to create a new task:

const data = {
  title: 'Buy groceries',
  description: 'Milk, eggs, bread',
  due_date: '2025-04-15 10:00:00',
  status: 'pending'
};
const record = await pb.collection('tasks').create(data);

The SDK returns the newly created record object with an id and timestamps. To list tasks owned by the current user with optional filters:

const records = await pb.collection('tasks').getList(1, 50, {
  filter: `user.id = "${pb.authStore.model.id}"`,
  sort: '-created'
});

Updating a record: await pb.collection('tasks').update(recordId, { status: 'completed' }); Deleting: await pb.collection('tasks').delete(recordId); The SDK also supports batch operations, expand relations, and custom HTTP calls. If you are using React, you can manage auth state via pb.authStore.onChange listener. For Vue or Svelte, a similar pattern works. The SDK is reactive – you can subscribe to real‑time changes, which we will cover in Step 6.

Error handling is important: if a request fails due to permission or validation errors, PocketBase returns a clear JSON error object with status, message, and data (containing field‑level errors). The SDK throws these as ClientResponseError so you can catch them in a try‑catch block. You can also make raw fetch calls to the REST API if you prefer, but the SDK simplifies token management and serialization. The SDK’s autoCancellation feature (enabled by default) prevents duplicate requests with the same tag.

Step 5: Handling File Uploads and Media Storage

PocketBase treats file uploads as a native field type. In the task collection, we added an attachment field of type File. To upload a file from the frontend, you simply include it in the form data when creating or updating a record. The SDK accepts Blob, File, or FormData objects. For example, if you have an HTML <input type="file"> element, you can access input.files[0] and pass it into the same create call:

const formData = new FormData();
formData.append('title', 'Design mockup');
formData.append('description', 'Figma file');
formData.append('due_date', '2025-04-20');
formData.append('attachment', fileInput.files[0]);
const record = await pb.collection('tasks').create(formData);

The SDK automatically detects that it’s a FormData and sets the appropriate content type. PocketBase will store the file in the filesystem under pb_data/storage/ with a unique name. The record’s attachment field will contain the filename (e.g., abc123_design.png). To generate a URL to serve the file, PocketBase provides a simple pattern: http://localhost:8090/api/files/{collection}/{recordId}/{filename}. You can also request thumbnails for images by appending ?thumb=100x200. The SDK has a helper pb.getFileUrl(record, fieldName) that constructs this URL automatically. File uploads are limited by the constraints you defined in the collection (max size, MIME types). If an upload fails, PocketBase returns a 400 error with validation details.

For production, consider using a cloud storage provider (like S3 or GCS) instead of the local filesystem, but PocketBase does not natively support external storage yet (the community has some experimental patches). For many apps, local storage with regular backups is sufficient. You can also mount an external volume in Docker setups. File deletion is automatic when you delete a record that contains a file field, or when you replace the file – the old file is removed from disk. This keeps your storage tidy.

Step 6: Implementing Real-Time Subscriptions for Live Data

One of PocketBase’s standout features is its built‑in real‑time engine via Server‑Sent Events (SSE). The SDK makes it trivial to subscribe to changes on a collection, a specific record, or even custom topics. For our task manager, we want to update the UI whenever a task is created, updated, or deleted by any user. To subscribe to all events in the tasks collection:

pb.collection('tasks').subscribe('*', function(e) {
  console.log(e.action); // 'create', 'update', 'delete'
  console.log(e.record); // the record object
  // update your local state accordingly
});

The subscribe method returns an unsubscribe function that you call when the component unmounts: const unsubscribe = ...; unsubscribe();. You can also subscribe to a specific record by passing its ID instead of '*'. The events include the full record snapshot for create/update, and the previous record for delete (with e.record still populated but with a @delete flag). This allows you to optimistically update the UI without having to refetch the entire list. Behind the scenes, PocketBase opens a single SSE connection per client and multiplexes subscriptions. The connection is resilient – if it drops, the SDK auto‑reconnects and resubscribes.

Using subscriptions effectively requires careful state management. For example, if you are using React, you can store tasks in a useState array and update it inside the subscribe callback. Be mindful of concurrency: when you create a task via the API, you might also receive a subscription event for it – you may want to deduplicate or use a local flag. PocketBase’s events are reliable, but for critical apps you should still handle the initial data load via getList and then merge real‑time changes. You can also use the @collection filter in subscription to receive only changes that match a condition (e.g., only tasks assigned to a specific user), but this feature is still evolving – currently you can filter by record ID or collection, but not arbitrary field values on the server side. For most use cases, subscribe to the whole collection and filter on the client.

Step 7: Deploying PocketBase to Production

Once your app is ready, you’ll want to run PocketBase on a server. Since it’s a single binary, deployment is straightforward. You can run it on a VPS (like DigitalOcean, Linode, or AWS EC2) behind a reverse proxy (Nginx or Caddy) to add SSL and domain routing. Many developers use PM2 or systemd to keep the process alive. Here is a simple systemd service file:

[Unit]
Description=PocketBase
After=network.target

[Service]
User=youruser
WorkingDirectory=/opt/pocketbase
ExecStart=/opt/pocketbase/pocketbase serve --dir=/opt/pocketbase/pb_data --http=0.0.0.0:8090
Restart=always

[Install]
WantedBy=multi-user.target

If you need HTTPS, you can either configure your reverse proxy to terminate SSL or use PocketBase’s built‑Let’s Encrypt support by setting the --https flag and providing a domain. However, the documentation recommends using a reverse proxy for better control. You should also set environment variables for the admin email and password via flags (e.g., --adminEmail and --adminPassword) to avoid interactive prompts on boot. For database backups, simply copy the pb_data/data.db file while the server is running (SQLite supports live backups) or use the admin UI’s export feature. For scaling, PocketBase is not designed for horizontal scaling because SQLite is single‑writer. If you anticipate high traffic, consider using a “read replicas” approach or migrating to a different backend. For most small to medium projects, PocketBase’s SQLite can handle thousands of concurrent users.

Another deployment option is using Docker. The official Docker image is pocketbase/pocketbase. You can mount a volume for persistent data and expose port 8090. For example:

docker run -d --name pocketbase -p 8090:8090 -v $(pwd)/pb_data:/pb_data pocketbase/pocketbase

Whether you choose Docker or a bare‑metal binary, PocketBase’s small footprint means you can even run it on a $5/month VPS. Monitoring logs is easy with the built‑in admin logs, or you can forward them to a centralized system. Remember to change the admin credentials after the first login and to regularly update the binary as PocketBase receives active development.

Tips and Best Practices for Using PocketBase

1. Use the Admin UI to Prototype, Then Automate with Migrations

When starting a new project, it is tempting to define all your collections and fields manually via the admin UI. This is fine for prototyping, but for production you should version‑control your schema. PocketBase supports “migrations” – JavaScript files that run in sequence to create or modify collections. You can write migration files in the pb_migrations folder (inside your data directory). The admin UI even has a “Migrations” section where you can generate a migration script from the current schema. Using migrations ensures that your team (and your deployment pipeline) can reproduce the exact same database structure. It also makes rollbacks easier. Always commit migration files to your repository.

2. Secure Your API Rules – Be Explicit

PocketBase’s API rules are powerful but can be a source of security holes if not carefully configured. Always start by denying all operations and then gradually open permissions. For example, do not set a list rule to @request.auth.id != "" if you want to show public data; instead, use @request.auth.id != "" || public = true. For fields that should never be exposed (like user passwords), PocketBase automatically excludes them from API responses. However, for custom fields, you can set “Hidden” properties in the schema. Test your rules using the API preview with different token values. Also, be aware of the $auto variable that can be used in rules to reference the created record’s values. Use it to enforce that, for example, a user can only update their own profile: id = @request.auth.id.

3. Optimize File Storage and Use Thumbnails

If your app handles many file uploads, disk space can become an issue. PocketBase does not support external storage natively, so you’ll need to plan for cleanup. You can set up a cron job to delete orphaned files (though PocketBase cleans up on record deletion). For image fields, always request thumbnails via the ?thumb=300x200 parameter to reduce bandwidth and load times. The SDK’s getFileUrl accepts options like {thumb: '100x100'}. Also, set appropriate file size and type limits in the collection schema to prevent abuse. If you expect lots of uploads, consider offloading to a CDN like Cloudflare, which can cache the file URLs.

Frequently Asked Questions about PocketBase

Q1: What exactly is PocketBase, and how does it compare to Firebase or Supabase?

PocketBase is an open‑source backend as a service that runs as a single binary. It includes an SQLite database, a REST API, an admin UI, authentication, file storage, and real‑time subscriptions. Compared to Firebase, PocketBase is self‑hosted (no vendor lock‑in) and uses SQLite instead of NoSQL. It is much simpler to set up than Supabase, which requires a full PostgreSQL stack. However, PocketBase lacks the scalability of Firebase’s Firestore and Supabase’s PostgreSQL for complex queries. It is best suited for small to medium applications, prototypes, and internal tools where ease of deployment and minimal overhead are priorities.

Q2: Can I use PocketBase with any frontend framework?

Yes. PocketBase exposes a standard REST API, so any HTTP client can interact with it. The official JavaScript SDK works with React, Vue, Svelte, Angular, and even plain HTML/JS. There are community SDKs for Dart (Flutter), Python, Swift, and more. You can also use the SDK with server‑side frameworks like Next.js (on the client side) or as a proxy via a backend‑for‑frontend pattern. Because PocketBase handles authentication and file serving, it integrates seamlessly with SPAs and mobile apps.

Q3: How do I handle database migrations when updating my schema?

PocketBase provides an official migration system. You create .js files inside the pb_migrations directory (located in your data folder). Each file exports an up and optional down function that use PocketBase’s Dao API to add, modify, or delete collections and fields. The admin UI has a “Migrations” panel where you can view applied migrations and even generate a migration from current schema changes. Always run pocketbase migrate after updating your code. For teams, store migration files in version control and apply them in order during deployment.

Q4: Is PocketBase production‑ready for a large number of concurrent users?

PocketBase’s core database is SQLite, which supports one writer at a time. For most applications with a few hundred to a few thousand concurrent users, SQLite performs excellently. However, for high‑traffic apps (tens of thousands of concurrent writes), you may encounter write contention. Solutions include using a read‑only replica for queries, batching writes, or migrating to a different backend (e.g., using PocketBase as an admin UI with a separate database). PocketBase is actively maintained, and the community is small but growing. Many production apps (including ones by the creator) run on PocketBase without issues. Always benchmark with your expected load.

Q5: How can I reset the admin password if I forget it?

If you forget your admin password, there are two ways to reset it. First, you can start PocketBase with the --superuserReset flag followed by the admin email: ./pocketbase serve --superuserReset=admin@example.com. This will prompt you to set a new password interactively. Second, you can directly manipulate the SQLite database file using a tool like sqlite3 and update the password hash (not recommended unless you know the hashing algorithm). The easiest route is the flag method – just stop the server, run it with the flag, follow the prompt, then remove the flag and restart.

Q6: Can I import data from another backend (like Firebase or a CSV) into PocketBase?

Yes. PocketBase’s API makes it easy to bulk import records. You can write a script that reads your existing data (e.g., from Firebase using its SDK) and then calls PocketBase’s create endpoint for each record, or use batch operations. For CSV files, you can parse them and map columns to your collection fields. There are community tools like PocketBase Importer that automate this. Because PocketBase uses SQLite, you can also directly import a SQL dump if you are migrating from another SQLite database, but be careful with IDs and relations.

Conclusion

PocketBase is a game‑changer for developers who want a fully functional backend without the overhead of managing a server stack or paying for a cloud BaaS. In this tutorial, we covered the entire lifecycle of using PocketBase – from installation and schema design to authentication, CRUD via the JavaScript SDK, file uploads, real‑time subscriptions, and production deployment. Along the way, we highlighted best practices like version‑controlling migrations, securing API rules, and optimizing file storage. PocketBase’s simplicity means you can go from zero to a working backend in minutes, yet its flexibility allows you to build complex, secure applications. The ecosystem is still young, but the core features are robust and well‑documented. Whether you are building a personal project, an internal tool, or a startup MVP, PocketBase gives you the power of a full backend with minimal effort. Download it, try it out, and experience the joy of self‑hosted backend development.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *