Overview
JavaScript hooks provide:- Hot reloading: Changes to your hooks are detected automatically (in dev mode)
- No compilation: Write JavaScript and see results immediately
- Full API access: Access to all PocketBase APIs through global bindings
- TypeScript support: Full TypeScript definitions for autocomplete and type checking
- npm packages: Use Node.js modules via
require()
Setup
1
Enable JSVM plugin
The JSVM plugin is included in the default PocketBase executable. If you’re building from source, ensure it’s registered:
main.go
2
Create hooks directory
Create a
pb_hooks directory in your project root:3
Create a hook file
Create a file ending in
.pb.js or .pb.ts:4
Write your first hook
Add some code to your hook file:
pb_hooks/main.pb.js
Configuration
The JSVM plugin accepts the following configuration options:Set
HooksPoolSize to a positive number (e.g., 15) to improve performance by pre-warming JavaScript runtime instances.Global bindings
PocketBase exposes several global objects and functions to your JavaScript hooks:Core objects
Hook registration functions
All event hooks are available as global functions:See the Event hooks reference for a complete list of available events.
Examples
Basic record hook
pb_hooks/posts.pb.js
Send email on record creation
pb_hooks/notifications.pb.js
Custom validation
pb_hooks/validation.pb.js
HTTP request
pb_hooks/webhooks.pb.js
Database queries
pb_hooks/stats.pb.js
Modify record before saving
pb_hooks/slugify.pb.js
Add custom routes
pb_hooks/routes.pb.js
Scheduled tasks
pb_hooks/cron.pb.js
TypeScript support
PocketBase automatically generates TypeScript definitions inpb_data/types.d.ts. Use .pb.ts extensions for full type checking:
pb_hooks/typed.pb.ts
Using npm packages
You can use Node.js modules viarequire():
1
Initialize npm
2
Install packages
3
Use in hooks
pb_hooks/example.pb.js
Best practices
Keep hooks focused
Keep hooks focused
Each hook file should handle a specific domain or feature. Split complex logic into multiple files:
Error handling
Error handling
Always handle errors appropriately:
Use async operations carefully
Use async operations carefully
JavaScript hooks run synchronously. For long-running operations, log and continue:
Tag your hooks
Tag your hooks
Use tags to filter which collections trigger your hooks:
Debugging
Console logging
Inspect objects
Development mode
Run PocketBase with the--dev flag for verbose logging:
Next steps
Event hooks reference
See all available event hooks
Custom routes
Learn about custom API endpoints