pb-hooks
하는 일
이 스킬은 JavaScript로 작성한 맞춤 서버 코드로 PocketBase 앱을 확장하도록 돕습니다. 기본 기능을 넘어서는 로직이 필요한 개발자에게 맞습니다.
사용하는 경우
- ✓PocketBase에 맞춤 API 경로가 필요할 때.
- ✓레코드가 생성되거나 수정될 때 코드를 실행하고 싶을 때.
- ✓예약 작업이나 PocketBase에서 나가는 HTTP 요청이 필요할 때.
스킬 링크
https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“주문 레코드가 새로 생성될 때마다 저에게 이메일을 보내는 PocketBase 훅을 작성해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
에이전트는 PocketBase가 제공하는 JavaScript 엔진을 사용해 pb_hooks 폴더에 .pb.js 파일을 작성합니다. 경로, 이벤트, 데이터베이스 조회, 이메일 기능을 씁니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 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. Usefunction(){}and CommonJSrequire(). - 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=25flag 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. Calle.next()to proceed.onRecord*AfterSuccess— runs after successful executiononRecord*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 |
자주 묻는 질문
최신 JavaScript 기능을 쓸 수 있나요?
전부는 아닙니다. 엔진은 ES5와 일부 ES6를 지원하며, 모듈과 async/await는 사용할 수 없습니다.
파일을 바꾸면 다시 로드되나요?
네. 훅 파일은 앱 시작 시 로드되고, 파일이 바뀌면 다시 로드됩니다.
훅끼리 데이터를 공유하나요?
아니요. 각 핸들러는 자기 컨텍스트에서 실행되므로 요청 사이에 공유 상태가 없습니다.
상세 정보
작성자의 원본 설명
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.
인기도
- GitHub 스타
- 33k
- 순위
- #8873
- 라이선스
- MIT
- 업데이트
- 2026. 11. 2.
댓글
- …
이 저장소의 다른 스킬
owasp-security
33k웹 앱, API, 모바일, 컨테이너, AI 에이전트를 위한 OWASP 보안 지침을 따르도록 해서, 흔한 약점을 찾고 수정안을 제안하게 합니다.
agent-management
33k에이전트가 AI Maestro 명령줄을 사용해 AI 에이전트를 만들고, 나열하고, 일시 정지하고, 깨우고, 이름을 바꾸고, 삭제하도록 돕습니다.
agent-messaging
33k에이전트가 Agent Messaging Protocol로 AI 에이전트 사이에 서명된 메시지를 보내고, 받고, 답하도록 돕습니다. 대부분 내 컴퓨터에서 작동합니다.
docs-search
33k에이전트가 자동 생성된 코드 문서에서 함수 시그니처, 클래스 정의, 주석을 검색하도록 해서, 코드를 바꾸기 전에 실제 API를 확인하게 합니다.
비슷한 스킬
api-connector-builder
280k에이전트가 기존 패턴을 따라 새로운 API 연결을 만들도록 합니다. 새로운 방식을 도입하지 않고 연동을 하나 더 추가할 때 씁니다.
api-design
280k에이전트가 모범 사례에 따라 REST API를 설계하도록 돕습니다. API가 통신하는 방식, 오류를 보여 주는 방식, 데이터를 정리하는 방식을 정하는 데 유용합니다.
backend-patterns
280k에이전트가 서버 쪽 아키텍처 패턴과 데이터베이스 최적화를 다루도록 돕습니다. 서버에서 실행되는 코드를 만들거나 검토할 때 유용합니다.