What is the JavaScript VM?
The JavaScript VM (JSVM) is a plugin that enables you to write server-side JavaScript code that runs directly in PocketBase. It uses the goja JavaScript runtime, which implements ECMAScript 5.1 with some ES6+ features.Getting started
To use JavaScript hooks in PocketBase, you need to:- Create a
pb_hooksdirectory in your project root - Add
.pb.jsor.pb.tsfiles to this directory - Write your JavaScript code using the PocketBase APIs
Files must end with
.pb.js or .pb.ts to be recognized by the JavaScript VM. The .pb.ts extension is recommended for better IDE support with TypeScript definitions.Basic example
Here’s a simple example that adds a custom route:File structure
Your PocketBase project structure should look like this:Available APIs
The JavaScript VM provides several namespaces and functions:Global variables
$app- The PocketBase application instance$template- Template rendering helpers__hooks- Absolute path to the hooks directory
Utility namespaces
$http- HTTP client for making requests$security- Cryptography and security utilities$filesystem- File system operations$os- Operating system utilities$filepath- File path utilities$dbx- Database query builder helpers$apis- API route helpers and middlewares$mails- Email sending utilities
Global functions
routerAdd()- Register custom HTTP routesrouterUse()- Register global middlewarescronAdd()- Schedule cron jobscronRemove()- Remove cron jobson*()- Event hooks (e.g.,onRecordCreate,onRecordUpdate)
TypeScript support
PocketBase automatically generates atypes.d.ts file in your pb_data directory with full TypeScript definitions. To use it:
- Create your hook files with
.pb.tsextension - Add a reference directive at the top of your file:
Hot reloading
During development, you can enable hot reloading to automatically restart PocketBase when your hook files change:Performance
The JavaScript VM uses a pool of runtime instances to handle concurrent requests efficiently. You can configure the pool size:Node.js compatibility
The JavaScript VM includes support for some Node.js modules:console- Logging to stdoutrequire()- Module loadingprocess- Process informationbuffer- Buffer operations
require() to load local modules or packages from node_modules.
Error handling
Errors in JavaScript hooks are automatically caught and returned as HTTP errors. You can throw errors or return them:Next steps
App instance
Learn about the global $app instance and its methods
Collections
Work with collections and schemas
Records
Create, read, update, and delete records
Events
Hook into PocketBase lifecycle events