Skip to content
Skillpedia
APIs & servers (backend)33k Β· #8873

pb-hooks

What it does

This skill helps you extend a PocketBase app with custom server code written in JavaScript. It is for developers who need logic beyond the built-in features.

When to use it

  • βœ“When you need a custom API route in PocketBase.
  • βœ“When you want code to run when a record is created or updated.
  • βœ“When you need a scheduled job or an outgoing HTTP request from PocketBase.

Skill link

https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.md

Copy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.

How to use

The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.

Ready-to-paste message

Use this skill to help me: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute β†’

Example of what to ask your AI

β€œWrite a PocketBase hook that emails me whenever a new order record is created.”

5 new skills a week. 1 minute to read.

How it works

The agent writes .pb.js files in the pb_hooks folder using the JavaScript engine PocketBase provides, with functions for routes, events, database queries and emails.

Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

PocketBase Server-Side JavaScript (pb_hooks)

Runtime Basics

  • Files go in pb_hooks/*.pb.js (must end with .pb.js)
  • Engine: goja β€” ES5.1 + some ES6. No ES6 modules (import/export), no async/await, no arrow functions in older versions. Use function(){} and CommonJS require().
  • Each file is loaded on app start and on hot-reload
  • __hooks β€” absolute path to the pb_hooks directory
  • TypeScript declarations: pb_data/types.d.ts (auto-generated, useful for IDE support)
  • --hooksPool=25 flag controls concurrent JS goroutines (default: 25)
  • Each handler runs in an isolated context β€” no shared mutable state between requests

Routing

Adding routes

routerAdd("GET", "/api/hello/{name}", function(e) {
    var name = e.request.pathValue("name")
    return e.json(200, { "message": "Hello " + name })
}, /* optional middleware */)

Path patterns

  • {name} β€” named path parameter
  • {path...} β€” wildcard (matches rest of path)
  • {$} β€” exact match (no trailing slash)

Response methods

Method Usage
e.json(status, data) JSON response
e.string(status, text) Plain text
e.html(status, html) HTML response
e.redirect(status, url) Redirect (301/302)
e.blob(status, contentType, bytes) Binary data
e.stream(status, contentType, reader) Streaming response
e.noContent(status) No body (204)

Reading request data

// Body (JSON)
var body = new DynamicModel({ name: "", age: 0 })
e.bindBody(body)

// Query params
var page = e.request.url.query().get("page")

// Headers
var token = e.request.header.get("Authorization")

// Uploaded files
var files = e.findUploadedFiles("document")  // returns array of *filesystem.File

// Auth state
var user = e.auth          // current auth record or null
var isSuper = e.hasSuperuserAuth()

Middleware

Built-in middleware

routerAdd("GET", "/api/protected", handler,
    $apis.requireAuth(),                // any authenticated user
    // OR
    $apis.requireAuth("users"),         // only "users" collection
    // OR
    $apis.requireSuperuserAuth(),       // superusers only
    // OR
    $apis.requireGuestOnly(),           // unauthenticated only
    // OR
    $apis.bodyLimit(5 * 1024 * 1024),   // 5MB body limit
    // OR
    $apis.gzip()                        // gzip compression
)

Global middleware

routerUse(function(e) {
    // runs before every request
    console.log(e.request.method, e.request.url.path)
    return e.next()  // MUST call e.next() to continue
})

Custom route middleware

function myMiddleware(e) {
    // pre-processing
    var result = e.next()  // call next handler
    // post-processing
    return result
}

routerAdd("GET", "/api/test", handler, myMiddleware)

Priority: middleware runs in order β€” first registered, first executed.

Event Hooks

Record lifecycle

Each record event has 3 variants:

  • onRecord*Execute β€” wraps the default action. Call e.next() to proceed.
  • onRecord*AfterSuccess β€” runs after successful execution
  • onRecord*AfterError β€” runs after execution error
// Before/during create
onRecordCreateExecute(function(e) {
    // e.record β€” the record being created
    e.record.set("status", "pending")
    return e.next()  // proceed with creation
}, "posts")  // optional collection filter

// After successful create
onRecordAfterCreateSuccess(function(e) {
    // e.record β€” the created record (has ID now)
    console.log("Created:", e.record.id)
}, "posts")

// After failed create
onRecordAfterCreateError(function(e) {
    // e.error β€” the error
    console.log("Failed:", e.error)
}, "posts")

All record hooks

Hook Event object fields
onRecordCreateExecute e.record
onRecordUpdateExecute e.record
onRecordDeleteExecute e.record
onRecordAfterCreateSuccess e.record β€” after successful create
onRecordAfterUpdateSuccess e.record β€” after successful update
onRecordAfterDeleteSuccess e.record β€” after successful delete
onRecordAfterCreateError e.record, e.error β€” after failed create
onRecordAfterUpdateError e.record, e.error β€” after failed update
onRecordAfterDeleteError e.record, e.error β€” after failed delete
onRecordValidate e.record β€” add custom validation errors
onRecordEnrich e.record β€” modify API respons
FAQ

Can I use modern JavaScript features?

Not all of them. The engine supports ES5 with some ES6, and modules and async/await are not available.

Does it reload when I change a file?

Yes. Hook files are loaded on app start and reloaded when they change.

Do requests share data between hooks?

No. Each handler runs in its own context, so there is no shared state between requests.

Details

Original description by the author

Server-side JavaScript hooks for PocketBase (pb_hooks). Use when writing custom routes, event hooks, cron jobs, sending emails, making HTTP requests, querying the database, or extending PocketBase with server-side logic. Covers the goja ES5 runtime, routing, middleware, all event hooks, DB queries, record operations, and global APIs.

repo: davila7/claude-code-templates

Popularity

GitHub stars
33k
Ranking position
#8873
License
MIT
Updated
11/2/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills