---
name: pocketbase
description: PocketBase backend patterns and API reference (Go). Use when working with PocketBase collections, authentication, records API, file handling, Go hooks/extensions, migrations, testing, or deployment. Covers both client-side SDK usage and server-side Go extensions.
user-invocable: false
---

# PocketBase Reference (Go)

PocketBase is an open-source backend with embedded SQLite, realtime subscriptions, built-in auth, a dashboard UI, and a REST API. This project uses it as a Go framework.

## Architecture Overview

- **Go package** initialized via `pocketbase.New()` -- requires Go 1.23+
- **Default endpoints**: `http://127.0.0.1:8090` (static), `/_/` (dashboard), `/api/` (REST API)
- **Data directory**: `pb_data/` (database + uploaded files)
- **Migrations**: `migrations/` (Go migration files)
- **Best used as**: Go framework with custom business logic + client-side SPA via REST API

## Scenario Guide

Choose the reference that matches your task:

### 1. Collections & Fields

Setting up data models, defining field types, configuring collection rules.

See [collections.md](references/collections.md) for:
- Base, Auth, and View collection types
- All field types (Bool, Number, Text, Email, URL, Editor, Date, Autodate, Select, File, Relation, JSON, GeoPoint) with modifiers
- API rules and filter syntax (`@request.auth`, `@request.body`, operators, macros)
- Access control patterns (role-based, ownership, managed, mixed)

### 2. Authentication

Implementing user login, registration, OAuth2, MFA, OTP, tokens, impersonation.

See [authentication.md](references/authentication.md) for:
- Password, OTP, OAuth2, and MFA authentication flows
- Token handling (stateless JWT, `Authorization: TOKEN` header)
- Impersonation and API keys
- Client-side SDK auth patterns (JS + Dart)

### 3. Records API (Client-Side)

CRUD operations on records via the REST API and JS/Dart SDKs.

See [records-api.md](references/records-api.md) for:
- List/search with pagination, sorting, filtering
- Create, update, delete records
- Batch operations
- Expanding relations (up to 6 levels, dot notation)
- Back-relations (`collection_via_field`)
- Field selection and excerpts

### 4. File Handling

Uploading, downloading, thumbnails, protected files, S3 storage.

See [files.md](references/files.md) for:
- Upload via SDK and FormData
- Append/delete file modifiers (`+` / `-`)
- File URL format and thumbnail generation
- Protected files with short-lived tokens
- Local vs. S3 storage configuration
- Server-side Go filesystem operations

### 5. Go Hooks & Routing (Server-Side)

Custom server-side logic: event hooks, custom API routes, middleware.

See [go-hooks-routing.md](references/go-hooks-routing.md) for:
- Event hook categories (App, Record, Auth, Mailer, Realtime, Collection)
- Hook pattern: `func(e *EventType) error { ... return e.Next() }`
- Custom routes via `se.Router.GET/POST/...()` and path parameters
- Route groups with `se.Router.Group()`
- Middleware with `Bind/BindFunc` and built-in middleware (`apis.RequireAuth`, etc.)
- Request/response handling (body, headers, files, JSON, HTML, redirect)
- Error responses (`e.BadRequestError`, `e.ForbiddenError`, etc.)

### 6. Go Database & Records (Server-Side)

Server-side database queries, record CRUD, transactions.

See [go-database-records.md](references/go-database-records.md) for:
- Query builder (`app.DB()`, select, where, join, order, limit)
- Expression helpers (`dbx.NewExp`, `dbx.HashExp`, `dbx.And`, `dbx.Or`, `dbx.Like`, etc.)
- Record find methods (`FindRecordById`, `FindFirstRecordByFilter`, `FindRecordsByFilter`)
- Record create/update/delete with `app.Save()` / `app.Delete()`
- Transactions with `app.RunInTransaction()`
- Expanding relations, access control, token generation
- Field value modifiers (`+`, `-`, `:autogenerate`)
- Record proxy pattern for typed access

### 7. Go Migrations

Versioning database schema, creating collections/superusers programmatically.

See [go-migrations.md](references/go-migrations.md) for:
- Migration setup with `migratecmd.MustRegister()`
- `m.Register(upFunc, downFunc)` pattern
- CLI commands (`migrate create`, `migrate up`, `migrate down`, `migrate collections`)
- Automigrate behavior
- Examples: raw SQL, settings init, superuser creation, collection creation

### 8. Go Utilities (Server-Side)

Emails, templates, HTTP, filesystem, logging, console commands, realtime messaging, cron jobs.

See [go-utilities.md](references/go-utilities.md) for:
- Sending custom emails (`app.NewMailClient()`, `mailer.Message`)
- HTML template rendering (`template.NewRegistry()`)
- Custom console commands (cobra)
- Realtime messaging via `app.SubscriptionsBroker()`
- Cron job scheduling (`app.Cron().MustAdd()`)
- Logging (`app.Logger()`, slog interface)
- Filesystem operations
- Security helpers (random strings, encryption)
- In-memory app store

### 9. Go Testing

Integration testing with `tests.TestApp` and `tests.ApiScenario`.

See [go-testing.md](references/go-testing.md) for:
- Test app setup with `tests.NewTestApp()`
- API scenario testing pattern
- Token generation for test users
- Test data preparation

### 10. Production Deployment

Deploying, configuring reverse proxies, Docker, backups, security hardening.

See [production.md](references/production.md) for:
- Building and deploying Go binary
- Systemd service configuration
- Reverse proxy setup (NGINX, Caddy)
- Docker deployment
- Backup/restore strategies
- Recommended settings (SMTP, MFA for superusers, rate limiting, encryption)

## Quick Reference

### Minimal main.go

```go
package main

import (
    "log"
    "net/http"
    "os"

    "github.com/pocketbase/pocketbase"
    "github.com/pocketbase/pocketbase/apis"
    "github.com/pocketbase/pocketbase/core"
)

func main() {
    app := pocketbase.New()

    app.OnServe().BindFunc(func(se *core.ServeEvent) error {
        // serve static files
        se.Router.GET("/{path...}", apis.Static(os.DirFS("./pb_public"), false))

        // custom route
        se.Router.GET("/api/myapp/hello/{name}", func(e *core.RequestEvent) error {
            name := e.Request.PathValue("name")
            return e.JSON(http.StatusOK, map[string]string{"message": "Hello " + name})
        })

        return se.Next()
    })

    if err := app.Start(); err != nil {
        log.Fatal(err)
    }
}
```

### Common Go Operations

```go
// Find records
record, err := app.FindRecordById("posts", "RECORD_ID")
records, err := app.FindRecordsByFilter("posts", "status='active'", "-created", 20, 0)

// Create record
collection, _ := app.FindCollectionByNameOrId("posts")
record := core.NewRecord(collection)
record.Set("title", "New Post")
err := app.Save(record)

// Auth
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
token, err := user.NewAuthToken()

// Transaction
app.RunInTransaction(func(txApp core.App) error {
    // use txApp for all operations
    return txApp.Save(record)
})
```

### JS SDK Client Setup (Frontend)

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

// Auth
await pb.collection('users').authWithPassword('email', 'password');

// CRUD
const list = await pb.collection('posts').getList(1, 20, { filter: 'status="active"', sort: '-created' });
const record = await pb.collection('posts').getOne('RECORD_ID', { expand: 'author,tags' });

// Realtime
pb.collection('posts').subscribe('*', (e) => { console.log(e.action, e.record) });
```

### Key Go Imports

```go
"github.com/pocketbase/pocketbase"           // main package
"github.com/pocketbase/pocketbase/core"       // core types (App, Record, Collection, etc.)
"github.com/pocketbase/pocketbase/apis"       // routing helpers, middleware
"github.com/pocketbase/pocketbase/tools/types"      // types.Pointer, types.DateTime
"github.com/pocketbase/pocketbase/tools/filesystem"  // file factories
"github.com/pocketbase/pocketbase/tools/mailer"      // email types
"github.com/pocketbase/pocketbase/tools/template"    // HTML templates
"github.com/pocketbase/pocketbase/tools/security"    // crypto helpers
"github.com/pocketbase/dbx"                  // DB expression builders
```
