# PocketPages > PocketPages v1 is a file-routed, server-rendered page framework built into PocketOne (the `pages` extension): EJS, JSX or Markdown pages in pb_pages/, rendered inside PocketBase's JavaScript VM with a `ctx` API for requests, auth, data and assets. PocketPages v1 runs in the `pocketone` binary, not Node; PocketPages 0.x (the npm package) is retired, see /docs/moving-from-0x. Agent Skill: https://github.com/pockethost/pocketone/tree/main/agent/skills/pocketpages (Claude Code: `/plugin marketplace add pockethost/pocketone`). --- Source: https://pocketpages.dev/docs/moving-from-0x # Moving from PocketPages 0.x PocketPages v1 is part of PocketOne (the `pages` extension). It keeps the ideas of the npm package (a folder of files that become routes, EJS, layouts, middleware, private partials) and changes the shapes. Apps written for 0.x don't run unchanged. There is no migration tool. Start a new app with `pocketone pages create `, then move your pages over using the list below. The npm package is being retired. ## Folder and boot | 0.x | v1 | |---|---| | `pb_hooks/pages/`, booted by `require('pocketpages')` in a `.pb.js` file | `pb_pages/` next to `pb_data`. No boot file, no npm install. | | `create-pocketpages` | `pocketone pages create [--starter ]` | Delete the `.pb.js` boot file and the `pocketpages` dependencies, and move the contents of `pb_hooks/pages/` to `pb_pages/`. ## The context object 0.x passed an `api` object and spread its members into each template. v1 passes one `ctx` object with `req`, `res`, `data`, `params`, `route` and helpers. See the [ctx reference](https://pocketpages.dev/docs/ctx). | 0.x | v1 | |---|---| | `request`, `response` | `ctx.req`, `ctx.res` | | `body()`, `formData` | `ctx.req.body()` | | `redirect(path)` | `ctx.res.redirect(path)` | | `response.redirect(path, status)` | `ctx.res.redirect(path, status)` (unchanged) | | `env()`, `store()`, `dbg()`, `info()`, `warn()`, `error()` | `ctx.env()`, `ctx.store()`, `ctx.log.debug()` / `info()` / `warn()` / `error()` | | `auth`, `request.auth` | `ctx.auth` | | `resolve(name)` | `ctx.resolve(name)` | Inside templates, `data`, `params`, `asset` and `meta` are still available without the `ctx.` prefix. The other 0.x template globals are gone, including `resolve`, `redirect` and `env`: use `ctx.resolve()`, `ctx.res.redirect()` and `ctx.env()`. ## Parameters, query strings and cookies - Query parameters are no longer mixed into `params`, and nothing is JSON-parsed for you. `ctx.params` holds route parameters only; read the query string with `ctx.req.query(name)`, which returns strings. - Cookies are strings. Pass `{ json: true }` to parse one: `ctx.req.cookie('prefs', { json: true })`. ## Middleware 0.x middleware either returned a value or called `next(extra)`, depending on how many arguments it declared. v1 has one signature: ```js module.exports = (ctx, next) => { ctx.data.user = ctx.auth return next() } ``` Put shared data on `ctx.data`. See [Middleware](https://pocketpages.dev/docs/middleware). ## Loaders `+load.js`, `+get.js`, `+post.js` and friends are replaced by one `+page.js` per folder that exports `load`, `get`, `post`, `put`, `patch` and `delete`. Returned objects are shallow-assigned into `ctx.data` (no deep merge). As in 0.x, every handler is optional and a page renders for any method, so templates that check the request method keep working (`request.method` becomes `ctx.req.method`). ```js // 0.x: +load.js module.exports = (api) => ({ products: $app.findAllRecords('products') }) // v1: +page.js module.exports = { load(ctx) { return { products: ctx.app.findAllRecords('products') } }, } ``` See [Loading Data](https://pocketpages.dev/docs/loading-data). ## JSON 0.x sent template output as JSON if it parsed as JSON. v1 never does. Send JSON with `ctx.res.json()`, usually from a `+api.js` file. See [API Routes and JSON](https://pocketpages.dev/docs/api-routes). ## Layouts and slots | 0.x | v1 | |---|---| | `` comments in the page | `slot('name', () => { %>...<% })` | | `slot` and `slots.name` in layouts | `slot()` and `slot('name')` | See [Layouts and Slots](https://pocketpages.dev/docs/layouts). ## Output `echo()` is gone. A template returns its text; anything you want in the output goes through a tag. For streaming, use `ctx.res.sse()`. ## Flash messages 0.x put the message in a `?__flash=` query parameter with `redirect(path, { message })`. v1 uses a one-time cookie: ```js return ctx.res.redirect('/account', { flash: 'Saved' }) ``` Read it on the next request with `ctx.flash()`. See [flash](https://pocketpages.dev/docs/ctx/flash). ## Assets `asset()` URLs now carry the first 12 hex characters of the file's SHA-256, not the full hash. ## Configuration and plugins - `+config.js` still takes plugin package names, which are loaded with `require` as before, but the packages must be v1 plugins: the 0.x `pocketpages-plugin-*` packages don't run on v1. `auth` and `realtime` are built in, EJS and Markdown are always on, and Datastar is an [add-on](https://pocketpages.dev/docs/plugins/datastar) you copy into `pb_pages/_private/` and list as `'datastar'`. Its API is 0.x's, with `signals()` added alongside `readSignals`. npm plugin package names and EJS options are gone. - `+config.js` must export an object (`module.exports = { ... }`). 0.x's function form, `module.exports = (api) => ({ ... })`, is an error. - A `package.json` at the app's root still works: bare `require('pkg')` looks in the app folder's `node_modules` after `pb_pages`. - EJS and Markdown are always on. `pocketpages-plugin-ejs` and `pocketpages-plugin-marked` have no v1 equivalent because they aren't needed. - The auth plugin no longer goes through the JS SDK over HTTP (`api.pb()`). Use `ctx.session.*`, which calls the app directly. See [Authentication](https://pocketpages.dev/docs/plugins/auth). See [+config.js](https://pocketpages.dev/docs/config) and [Plugins](https://pocketpages.dev/docs/plugins). ## Behavior that changed quietly These don't fail with an error, so check for them when porting: - **Cookies are `HttpOnly` by default.** Pass `{ httpOnly: false }` to `ctx.res.cookie` for a cookie your page's JS reads. The `pb_auth` cookie stays `HttpOnly`, so `pb.authStore.loadFromCookie(document.cookie)` in the browser no longer works. - **Realtime messages are JSON-encoded.** `ctx.realtime.send(topic, data)` sends `JSON.stringify(data)`, so a string (such as an HTML fragment) arrives in quotes: `JSON.parse` it on the client. A `filter` now gets one argument, the client, and only narrows clients already subscribed to the topic. - **`.md`, `.jsx` and `.tsx` files are always pages**, never served as static files. - **Front matter is plain YAML.** EJS tags inside it aren't run. - **`require` never leaves `pb_pages`.** To load code from `pb_hooks`, use `require(__hooks + '/lib/x')`. - **Hook files (`*.pb.js`) go in `pb_hooks`.** In `pb_pages` they're an error and aren't served. ## Removed globals | 0.x | v1 | |---|---| | `url()` | `ctx.req.url` | | `stringify()` | `JSON.stringify` | | micro-dash | plain JavaScript | | `pb()` (JS SDK plugin) | `ctx.pb()`, built in: same SDK, no host setting, runs in-process as the signed-in user | ## Routing A route with fewer segments no longer matches a longer URL. Segment counts must match: `products/[id].ejs` serves `/products/123` but not `/products/123/reviews`. --- Source: https://pocketpages.dev/docs/agents # Coding agents Coding agents tend to write PocketPages as if it were a Node framework, or as if it were the 0.x npm package. The `pocketpages` Agent Skill teaches them v1: `pb_pages/`, `ctx`, routing, templates, layouts, auth and deploying. It's built from these docs and the v1 spec, so it changes when they change. **Claude Code** ``` /plugin marketplace add pockethost/pocketone /plugin install pocketone@pocketone ``` The plugin also has the `pocketone` skill, for the binary, `pocketone.yaml` and its extensions. **Other agents that read Agent Skills** (Cursor, Codex, Gemini CLI and others) ```bash npx skills add pockethost/pocketone ``` Or copy [`agent/skills/pocketpages`](https://github.com/pockethost/pocketone/tree/main/agent/skills/pocketpages) into your project. ## llms.txt - [pocketpages.dev/llms.txt](https://pocketpages.dev/llms.txt) indexes every docs page with a one-line summary. - [pocketpages.dev/llms-full.txt](https://pocketpages.dev/llms-full.txt) holds every docs page in one Markdown file. --- Source: https://pocketpages.dev/docs/installation # Installation PocketPages v1 is built into PocketOne as the `pages` extension (`ext/pages`). There is nothing to install from npm: the standard `pocketone` binary includes it. <%- include('quickstart') %> `pocketone pages create myapp` creates a new app. Add `--starter ` to start from a [starter kit](https://pocketpages.dev/docs/starter-kits). _Note: `--dir` tells `pocketone` where `pb_data` is. PocketPages looks for `pb_pages` next to it. Create the superuser before the first `serve`; otherwise PocketBase opens its superuser installer in your browser._ Browse to `http://localhost:8090` and you'll see the starter's home page. The default `minimal` kit is one splash page: <%- include('browser', { content: `

PocketPages

` }) %> To start editing, open ``` myapp/pb_pages/index.ejs ``` Changes appear on the next refresh. The app doesn't restart. ## Where pages live Pages live in their own folder next to PocketBase's others: ``` myapp/ pb_data/ pb_hooks/ pb_migrations/ pb_public/ pb_pages/ ``` - PocketPages finds the folder at `pb_pages` next to `pb_data`, or wherever `--pagesDir` points. - If the folder doesn't exist, the extension does nothing for that app. - Under a multitenant host, every instance has its own `pb_pages`. ## How does it work? PocketPages is a multi-page app server for PocketOne. It listens for requests and renders pages using file-based routing rules, like old-school PHP. URLs under `/api/` and `/_/` always belong to PocketBase. A URL nothing in `pb_pages` matches goes on to `pb_public`, then to PocketBase. --- Source: https://pocketpages.dev/docs/starter-kits # Starter Kits To start a new app from a starter kit, run: ```bash pocketone pages create myapp --starter ``` Without `--starter`, `pocketone pages create myapp` creates a plain app (the `minimal` kit). `pocketone pages starters` lists the kits. The folder must not exist yet. Then run it: ```bash cd myapp pocketone serve --dir ./pb_data ``` `pocketone` keeps `pb_data` next to its executable unless you pass `--dir`; `pb_pages` and `pb_migrations` are found next to `pb_data`. Each starter kit is an ordinary `pb_pages` folder written against the v1 API, so everything in these docs applies to it. | Starter | What it shows | Live demo | | --- | --- | --- | | **minimal** | A minimal PocketPages starter with just the basics | [pocketpages-minimal.pockethost.io](https://pocketpages-minimal.pockethost.io) | | **mvp** | MVP.css, a minimalist classless CSS framework | [pocketpages-mvp.pockethost.io](https://pocketpages-mvp.pockethost.io) | | **auth** | Password, anonymous, OTP and OAuth2 sign-in, plus verification, password reset and email change | [pocketpages-auth.pockethost.io](https://pocketpages-auth.pockethost.io) | | **daisyui** | Tailwind CSS with DaisyUI components | [pocketpages-daisyui.pockethost.io](https://pocketpages-daisyui.pockethost.io) | | **daisyui-docs** | Documentation site template with DaisyUI and navigation | [pocketpages-daisyui-docs.pockethost.io](https://pocketpages-daisyui-docs.pockethost.io) | | **htmx** | HTMX integration for dynamic interactions | [pocketpages-htmx.pockethost.io](https://pocketpages-htmx.pockethost.io) | | **datastar** | Realtime chat and counter using Datastar | [pocketpages-datastar.pockethost.io](https://pocketpages-datastar.pockethost.io) | --- Source: https://pocketpages.dev/docs/creating-a-page # Creating a PocketPages Page A **page** is a template file, `.ejs` or `.md`, anywhere in `pb_pages/`. Its path becomes its URL. ## Creating pages 1. **Create a file**: inside `pb_pages/`, create an `.ejs` file. For example, an "About" page: ```text pb_pages/about.ejs -> serves "/about" ``` 2. **`index` files**: `index` maps to its folder. ```text pb_pages/index.ejs -> serves "/" pb_pages/products/index.ejs -> serves "/products" (and "/products/") ``` 3. **Nested pages**: folders become URL segments. ```text pb_pages/ ├── index.ejs -> "/" ├── about.ejs -> "/about" ├── contact.ejs -> "/contact" └── products/ ├── index.ejs -> "/products" └── details.ejs -> "/products/details" ``` 4. **Markdown pages**: a `.md` file works the same way. It runs through EJS first, then Markdown. See [Markdown](https://pocketpages.dev/docs/markdown). ```text pb_pages/docs/routing.md -> "/docs/routing" ``` The extension is always dropped from the URL. To add data or handle forms, put a `+page.js` next to the page; see [Loading Data](https://pocketpages.dev/docs/loading-data). --- Source: https://pocketpages.dev/docs/directory-structure # Directory Structure All pages live in the `pb_pages/` folder, next to `pb_data/`: ``` myapp/ pb_data/ pb_hooks/ pb_migrations/ pb_public/ pb_pages/ +config.js +layout.ejs index.ejs about.ejs _private/ nav.ejs assets/ app.css products/ [id]/ +page.js index.ejs ``` ## Special names A file or folder name starting with one of these characters is never a URL: | Prefix | Meaning | |---|---| | `+` | Framework file: `+layout.ejs` (or `.jsx`, `.tsx`), `+middleware.js`, `+page.js`, `+api.js`, one of each per folder. `+config.js`, `+error.ejs` and `+404.ejs` are allowed only at the top of `pb_pages`. Any other `+` name, any other extension (such as `+layout.md`), and a top-only file in a subfolder are errors at startup. | | `_` | Private. `_private/` folders hold partials and modules for `include()` and `ctx.resolve()`. Other `_` names are ignored. | | `-` | Ignored (drafts, notes). | | `.` | Ignored (dotfiles), except a top-level `.well-known/`, which is served as static files (ACME challenges, `security.txt`, app links). | `node_modules/` is never routed either. ## Groups A folder named `(name)` groups files without adding a URL segment: `(marketing)/pricing.ejs` serves `/pricing`. A group can have its own `+layout.ejs`, `+middleware.js` and `_private/`. ## What else - Every other file is a [static file](https://pocketpages.dev/docs/static-content), served as-is. - Page code can `require()` modules by name from `_private/` folders (nearest first), then `pb_pages/node_modules`, then `pb_hooks/node_modules` and the app folder's `node_modules`, then the app's usual module paths. - Pages' own file access (routes, static files, includes, assets) never leaves `pb_pages`. - A `pb_pages/api/` folder is an error at startup, because `/api/` belongs to PocketBase. --- Source: https://pocketpages.dev/docs/routing # File-Based Routing URLs come from the files and folders in `pb_pages/`. ## Pages | File | URL | |---|---| | `index.ejs` | `/` | | `about.ejs` | `/about` | | `docs/index.md` | `/docs` (and `/docs/`) | | `docs/routing.md` | `/docs/routing` | | `products/[id].ejs` | `/products/123`, with `ctx.params.id = "123"` | | `[org]/[repo]/index.ejs` | `/acme/web`, with `ctx.params = { org: "acme", repo: "web" }` | - The extension is dropped. `index` maps to its folder. - `[name]` matches exactly one non-empty segment. A parameter must be the whole segment: `post-[id].ejs` is an error at startup. - Segment counts must match: `products/[id].ejs` doesn't match `/products/123/reviews`. - A URL with a trailing slash matches the same route as without it. Pages never redirect to add or remove one. - Matching is case-sensitive. See [Accessing Parameters](https://pocketpages.dev/docs/parameters). ## Groups A folder named `(name)` doesn't add a URL segment. Use groups to give part of the site its own layout or middleware: ```text pb_pages/ (site)/ +layout.ejs # wraps everything in (site) index.ejs # / about.ejs # /about xapi/ count.ejs # /xapi/count, outside the (site) layout ``` ## API routes A `+api.js` file serves its folder's URL without a template: `feeds/rss/+api.js` serves `/feeds/rss`. `[param]` folders work as for pages. A folder can't have both a `+api.js` and an `index` page. See [API Routes and JSON](https://pocketpages.dev/docs/api-routes). A `+page.js` in a folder with no page serves the folder's URL from JS too: `logout/+page.js` serves `/logout`. See [Pages without a template](https://pocketpages.dev/docs/loading-data#pages-without-a-template). ## Static files Every other file is served as-is at its path, with groups removed: `assets/app.css` serves `/assets/app.css`. See [Static content](https://pocketpages.dev/docs/static-content). ## Which route wins 1. `/api/...` and `/_/...` belong to PocketBase. Pages never see them. 2. Among matching routes the most specific wins: segments are compared from the left, and a literal segment beats a `[param]`. So `products/new.ejs` beats `products/[id].ejs` for `/products/new`. 3. A static file and a page can't claim the same URL (startup error). 4. A URL nothing in `pb_pages` matches goes on to `pb_public`, then to PocketBase. ## When routes change The route table is built when the app starts and rebuilt whenever anything in `pb_pages` changes. A rebuild never restarts the app or reloads `pb_hooks`. Startup errors (bad names, conflicts) are logged with the file path, and the previous route table keeps serving. --- Source: https://pocketpages.dev/docs/parameters # Route and Query Parameters Route parameters come from the URL path. Query parameters come from the query string. v1 keeps them apart. ## Route parameters Use square brackets in file or folder names to capture a URL segment: ``` pb_pages/ products/ [productId]/ index.ejs reviews/ [reviewId].ejs ``` This handles URLs like `/products/123` and `/products/123/reviews/456`. Read them through `params` (the same object as `ctx.params`): ```ejs

Product: <%= params.productId %>

Review: <%= params.reviewId %>

``` Route parameters are always strings. `ctx.params` never includes query parameters. ## Query parameters Read the query string with `ctx.req.query()`: ``` /products/123?sort=latest&tag=red&tag=blue ``` ```ejs

Sort by: <%= ctx.req.query('sort') %>

Tags: <%= ctx.req.query('tag', { all: true }).join(', ') %>

``` | Call | Returns | |---|---| | `ctx.req.query(name)` | First value as a string, or `undefined` | | `ctx.req.query(name, { all: true })` | Every value, as an array of strings | | `ctx.req.query()` | `{ name: firstValue }` for every parameter | Values are strings. Nothing is parsed for you; if you pass JSON in a query parameter, parse it yourself: ```js const filters = JSON.parse(ctx.req.query('filters') ?? '{}') ``` ## The route itself `ctx.route` describes the matched route: `{ path, name, file }`. For `products/[productId]/index.ejs`, `path` is `/products/[productId]`, `name` is `index`, and `file` is `products/[productId]/index.ejs`. --- Source: https://pocketpages.dev/docs/loading-data # Loading Data in PocketPages You can load data right in a template, or in a `+page.js` file next to it. ## Inline data loading The simplest way is a `<% %>` block at the top of your template: ```ejs <% const products = ctx.app.findRecordsByFilter('products', 'active = true', 'name', 100) %>

Products

<% for (const product of products) { %>

<%= product.getString('name') %>

<% } %> ``` ## Server script blocks For better formatting support in editors, you can write `

Products by Category

<% for (const category of categories) { %>

<%= category.getString('name') %>

<% } %> ``` ## Structured loading with `+page.js` A `+page.js` file keeps data loading and form handling out of the template: ```js // pb_pages/products/[id]/+page.js module.exports = { load(ctx) { ctx.data.product = ctx.app.findRecordById('products', ctx.params.id) }, post(ctx) { const { qty } = ctx.req.body() // ... return ctx.res.redirect(`/products/${ctx.params.id}`, { flash: 'Added to cart' }) }, } ``` ```ejs

<%= data.product.getString('name') %>

<% const flash = ctx.flash() %> <% if (flash) { %>

<%= flash %>

<% } %> ``` ### Exports `+page.js` exports any of `load`, `get`, `post`, `put`, `patch` and `delete`. 1. `load` runs first, for every method. 2. Then the handler for the request method runs, if there is one. 3. Then the page renders. A handler can set fields on `ctx.data`, or return a plain object. A returned object is shallow-assigned into `ctx.data` (`Object.assign`); there is no deep merge. ```js module.exports = { load(ctx) { return { departments: ctx.app.findAllRecords('departments') } }, get(ctx) { ctx.data.mode = 'view' }, } ``` If a handler sends a response (`ctx.res.redirect`, `json`, `html`, `text`, `file`, `sse`), the page doesn't render. ### One `+page.js` per folder A `+page.js` applies to every page in its folder. Use `ctx.route.name` to tell them apart: ```js module.exports = { load(ctx) { if (ctx.route.name === 'details') { ctx.data.reviews = ctx.app.findRecordsByFilter('reviews', 'product = {:id}', '-created', 20, 0, { id: ctx.params.id }) } }, } ``` ### Methods without a handler Every handler is optional. A page renders for any method, like PHP, so a template can handle a form on its own: ```ejs <% if (ctx.req.method === 'POST') { %>

Thanks, <%= ctx.req.body().name %>!

<% } else { %>
<% } %> ``` A `post` (or `put`, ...) handler in `+page.js` is the tidier place for form logic as a page grows, but you don't need one. Only routes with nothing to render, [`+api.js`](https://pocketpages.dev/docs/api-routes) and a `+page.js` without a page, answer `405` for a method they have no handler for. ## Example: a contact form ```js // pb_pages/contact/+page.js module.exports = { load(ctx) { return { departments: ctx.app.findAllRecords('departments') } }, post(ctx) { const { email, message, department } = ctx.req.body() try { const record = new Record(ctx.app.findCollectionByNameOrId('messages')) record.set('email', email) record.set('message', message) record.set('department', department) ctx.app.save(record) } catch (e) { return { error: 'Failed to send message', values: { email, message, department } } } return ctx.res.redirect('/contact', { flash: 'Thanks, we got your message.' }) }, } ``` ```ejs <% const flash = ctx.flash() %> <% if (flash) { %>

<%= flash %>

<% } %> <% if (data.error) { %><%= data.error %><% } %>
``` ## Pages without a template A `+page.js` in a folder with no page file serves the folder's URL from JS. Use it for a page you'd rather build in code, or for a URL that only acts and redirects: ```js // pb_pages/logout/+page.js module.exports = { post(ctx) { ctx.session.signOut() return ctx.res.redirect('/') }, } ``` ```js // pb_pages/hello/+page.js module.exports = { get(ctx) { return ctx.res.html(`

Hello ${ctx.auth ? ctx.auth.getString('name') : 'there'}

`) }, } ``` - With no template to render, each handler must send a response; returning without one is a 500. - Methods without a handler answer `405`, `GET` included: `/logout` above only takes `POST`. - Folder middleware runs; layouts don't, so wrap HTML yourself (or render a partial with `ctx.include`). - Errors show your `+error.ejs` page. For JSON responses and JSON errors, use [`+api.js`](https://pocketpages.dev/docs/api-routes) instead. ## Middleware or `+page.js`? - Only the route's own folder's `+page.js` runs. - Every `+middleware.js` from `pb_pages/` down to the route's folder runs, root first. Use [middleware](https://pocketpages.dev/docs/middleware) for data or checks that a whole section of the site shares. --- Source: https://pocketpages.dev/docs/api-routes # API Routes and JSON A `+api.js` file serves its folder's URL without a template. Use it for JSON, feeds, webhooks and anything else that isn't an HTML page. ```js // pb_pages/feeds/latest/+api.js module.exports = { get(ctx) { const posts = ctx.app.findRecordsByFilter('posts', 'published = true', '-created', 20) return ctx.res.json(posts.map((p) => ({ id: p.id, title: p.getString('title') }))) }, } ``` A request to `/feeds/latest` returns: ```json [{ "id": "abc123", "title": "Hello" }] ``` ## How it works - `+api.js` has the same exports as `+page.js`: `load`, `get`, `post`, `put`, `patch`, `delete`. - There is no template, so a handler must send a response. Returning without one is a `500`. - `[param]` folders work as for pages: `products/[id]/+api.js` serves `/products/123`. - A folder can't have both a `+api.js` and an `index` page. - Middleware runs for API routes too. - `ctx.httpError()` thrown in a `+api.js` answers with JSON: `{ "status": 404, "message": "..." }`. ## Sending responses | Call | Sends | |---|---| | `ctx.res.json(data)` / `ctx.res.json(status, data)` | JSON | | `ctx.res.text(text)` / `ctx.res.text(status, text)` | Plain text | | `ctx.res.html(html)` / `ctx.res.html(status, html)` | HTML as-is, without layouts | | `ctx.res.file(path)` | A file from `pb_pages` | | `ctx.res.redirect(location)` | A redirect | | `ctx.res.sse()` | A `text/event-stream` | See [res](https://pocketpages.dev/docs/ctx/res). ## JSON from a page JSON is only sent through `ctx.res.json` (or a `+api.js`). Template output is never parsed as JSON, even if it looks like JSON. A page's `+page.js` can still answer with JSON for one method: ```js // pb_pages/products/[id]/+page.js module.exports = { post(ctx) { const product = ctx.app.findRecordById('products', ctx.params.id) return ctx.res.json({ id: product.id, name: product.getString('name') }) }, } ``` ## Keep `/api/` free `/api/` belongs to PocketBase. Pages never see it, and a `pb_pages/api/` folder is an error at startup. Put your routes somewhere else, such as `feeds/`, `xapi/` or `hooks/`. --- Source: https://pocketpages.dev/docs/ejs # EJS EJS is always on. There is nothing to install or configure. ## Tags | Tag | Meaning | |---|---| | `<% code %>` | Run JS, no output | | `<%= expr %>` | Output, HTML-escaped | | `<%- expr %>` | Output, raw | | `<%# comment %>` | Nothing | | `<%%` | A literal `<%` | | `-%>` | Also remove the newline right after the tag | | `<%_` / `_%>` | Also remove whitespace before / after the tag on its line | | `` | Same as `<% code %>` | ## Escaping `<%= %>` replaces `&` `<` `>` `"` `'` with `&` `<` `>` `"` `'`. `null` and `undefined` output as an empty string. ```ejs

<%= '"x"' %>

<%- 'raw' %>

<%= null %>

``` Use `<%-` only for HTML you trust, such as the output of `include()` or `slot()`. ## In scope Inside a template you can use: | Name | | |---|---| | `ctx` | The [request context](https://pocketpages.dev/docs/ctx) | | `data` | `ctx.data` | | `params` | `ctx.params` | | `include` | Render a [partial](https://pocketpages.dev/docs/partials) | | `slot` | Define or read a [slot](https://pocketpages.dev/docs/layouts) | | `asset` | `ctx.asset` | | `meta` | `ctx.meta` | | `require` | Load a module: a path, or a name looked up in `_private/` then `node_modules` (see [JavaScript Runtime](https://pocketpages.dev/docs/jsvm)) | ## Output A template returns its text. There is no `echo()`; anything you want in the output goes through a tag. ```ejs
    <% for (const n of [1, 2]) { -%>
  • <%= n %>
  • <% } -%>
``` ## Caching A template is compiled once per content hash and reused, so an edited file is recompiled on the next request. --- Source: https://pocketpages.dev/docs/markdown # Markdown Support A `.md` file is a page, just like an `.ejs` file. Markdown is always on. ## How it works 1. **EJS first**: the file runs through EJS, so every [EJS tag](https://pocketpages.dev/docs/ejs) works in Markdown. 2. **Then Markdown**: the result is rendered as Markdown: CommonMark plus GFM tables, strikethrough, task lists and autolinks. ## Front matter YAML between `---` lines at the top of the file is front matter. Each top-level key is passed to `ctx.meta(key, value)`: ```markdown --- title: My Blog Post description: A detailed guide about something interesting --- # Content starts here... ``` Read the values in a layout with `meta`: ```ejs <%= meta('title') %> ``` ## Headings Headings get `id`s, so you can link to them: the text is lowercased, characters other than `a-z`, `0-9`, `-`, `_` and space are removed, and spaces become `-`. `## Front matter` gets `id="front-matter"`. ## Images Relative image paths go through [`ctx.asset`](https://pocketpages.dev/docs/ctx/asset), so they get fingerprinted URLs: ```markdown ![Logo](logo.png) ``` ## Markdown partials A `.md` file in a `_private/` folder can be included from EJS with `include()`. It's rendered the same way, EJS then Markdown: ```ejs <%- include('intro') %> ``` ## Notes - Layouts are `+layout.ejs`, `+layout.jsx` or `+layout.tsx`. A layout can't be Markdown: `+layout.md` is an error at startup. A Markdown page is still wrapped by the layouts above it. --- Source: https://pocketpages.dev/docs/jsx # JSX and TSX A `.jsx` or `.tsx` file is a template, just like an `.ejs` file. It can be a page, a layout (`+layout.tsx`), an error page (`+error.tsx`, `+404.tsx`) or a partial in `_private/`. PocketOne compiles it the first time it's used, with esbuild built into the binary: no Node, no `npm install`, no build step. TypeScript types are stripped, not checked. ```tsx // pb_pages/products/[id].tsx import Price from './_private/Price' export default function Product({ data, slot }: any) { slot('title', data.product.getString('name')) return (

{data.product.getString('name')}

) } ``` ```tsx // pb_pages/products/_private/Price.tsx export default ({ cents }: { cents: number }) => ${(cents / 100).toFixed(2)} ``` ## Props The file's default export is a component: a function from props to markup. It gets: | Prop | | |---|---| | `ctx` | The [request context](https://pocketpages.dev/docs/ctx). | | `data`, `params`, `meta` | The same as `ctx.data`, `ctx.params` and `ctx.meta`. | | `asset`, `include` | The same helpers EJS templates have. `include(name, locals)` returns HTML you can put in JSX. | | `slot` | `slot(name)` reads a named slot, `slot(name, content)` sets one, `slot()` is the inner content. | | `children` | In a layout, the inner content. | A partial also gets the locals it was included with, as props. EJS can include a `.jsx` or `.tsx` partial the same way: its locals become props. ## Server-rendered HTML only JSX renders straight to HTML on the server. There's no virtual DOM, no hydration and no client-side React. - Event handler props (functions) are dropped. Use plain attributes: `onclick="..."`, `hx-get`, `data-on:click`. - Text and attribute values are escaped. `dangerouslySetInnerHTML={{ __html: html }}` inserts raw HTML. - `class` and `className` both work, as do `for` and `htmlFor`. - `style` takes a string or an object: `{ marginTop: 4 }` renders `margin-top:4`. - `true` renders a bare attribute. `false`, `null` and `undefined` leave it out. - `` gets `` in front of it, since JSX can't write a doctype. ## Layouts ```tsx // pb_pages/+layout.tsx export default function Layout({ children, slot }: any) { return ( {slot('title')} {children} ) } ``` Layouts in `.ejs`, `.jsx` and `.tsx` mix freely: an EJS page can sit inside a TSX layout and the other way round. ## TypeScript modules `+page.ts`, `+api.ts`, `+middleware.ts`, `+config.ts` and any `.ts` file reached by `require` or `import` work like their `.js` versions. A module whose only export is `export default` behaves like `module.exports = ...`. Components are ordinary modules, so `import Card from './_private/Card'` resolves the same way as [`require`](https://pocketpages.dev/docs/jsvm). When a partial name has no extension, `.ejs`, `.md`, `.jsx` and `.tsx` are tried, in that order. --- Source: https://pocketpages.dev/docs/partials # Using Partials in PocketPages Partials are reusable templates that you include from other templates. They live in `_private/` folders, which are never routed. ## Including a partial ```ejs <%- include('nav') %> <%- include('card', { product }) %> ``` - `include(name, locals?)` renders a template from a `_private/` folder and returns its text. Use `<%-` so its HTML isn't escaped. - `name` may omit the extension; `.ejs`, `.md`, `.jsx` and `.tsx` are tried, in that order. - The partial sees the same `ctx`, plus `locals` as top-level variables. - `locals` is also the whole object, as in EJS. Use it for optional values: `<%= title %>` throws if `title` wasn't passed, but `<% if (locals.subtitle) { %>` doesn't. - Including more than 32 levels deep is an error. ## Where partials are found ``` pb_pages/ _private/ header.ejs footer.ejs blog/ _private/ sidebar.ejs posts/ _private/ post-card.ejs index.ejs ``` PocketPages looks in `_private/` in the current template's folder, then in each parent folder up to `pb_pages/`. ```ejs <%- include('post-card', { post }) %> <%- include('sidebar') %> <%- include('header') %> ``` A name starting with `/` looks only in `pb_pages/_private/`: ```ejs <%- include('/header') %> <%- include('/blog/_private/sidebar') %> ``` The extension is optional. A dotted name such as `include('nav.main')` finds `nav.main.ejs`. This means you can: - Keep section-specific partials in that section's `_private/`. - Hoist a shared partial up to a common parent. - Override a parent's partial with a local one of the same name, and still reach the root one with `/name`. ## Passing data Pass only what the partial needs: ```ejs <%- include('user-card', { name: user.getString('name'), joined: user.getString('created') }) %> ``` ```ejs

<%= name %>

Joined <%= joined %>

``` Partials can also read `ctx`, `data` and `params` directly. Passing values explicitly keeps them easy to reuse. ## Markdown partials A `.md` partial is rendered as EJS, then Markdown: ```ejs <%- include('intro') %> ``` ## JavaScript modules `_private/` folders also hold JS modules. Load them with [`ctx.resolve()`](https://pocketpages.dev/docs/ctx/resolve), which uses the same lookup. --- Source: https://pocketpages.dev/docs/layouts # Layouts and Slots `+layout.ejs` files wrap pages. A page's layouts are every `+layout` from its own folder up to `pb_pages/`, applied innermost first. A folder may have one layout, written as `+layout.ejs`, `+layout.jsx` or `+layout.tsx`. A layout can't be Markdown: `+layout.md` is an error at startup. ```plaintext pb_pages/ +layout.ejs # applied last (outermost) products/ +layout.ejs # applied first [id].ejs ``` For `/products/123`, `[id].ejs` renders, then `products/+layout.ejs` wraps it, then `+layout.ejs` wraps that. ## `slot()` In a layout, `slot()` returns the content being wrapped: the page, or the inner layout. ```ejs My Application
<%- slot() %>
© <%= new Date().getFullYear() %> My Application
``` `<%- slot %>` without parentheses prints the same content, so 0.x layouts that wrote it still work. ## Named slots A page (or an inner layout) defines a named slot with `slot(name, fn)`. `fn`'s output is captured and nothing is output in place. A layout reads it with `slot(name)`, which returns `''` if it isn't defined. ```ejs <% slot('title', () => { %><%= data.product.getString('name') %><% }) %>

<%= data.product.getString('name') %>

``` ```ejs <%- slot('title') || 'My shop' %> <%- slot() %> ``` - Named slots defined by the page or by any inner layout are visible to every outer layout. - Defining the same name again replaces it. Inside the new definition's `fn`, `slot(name)` still returns the previous content, so a layout can wrap it: ```ejs <% slot('title', () => { %>Docs: <%- slot('title') %><% }) %>
<%- slot() %>
``` ## Data in layouts Layouts render after the page, with the same `ctx`. Everything middleware, `+page.js` and the page put on `ctx.data` or `ctx.meta` is there. ## When layouts are skipped - When the response isn't HTML (a handler set another `Content-Type`). - When a handler or middleware sent the response itself (`ctx.res.json`, `ctx.res.html`, `ctx.res.redirect`, ...). - For `+api.js` routes, which have no template. - After `ctx.res.layout(false)`, called from middleware, `+page.js` or the page itself. - With the [Datastar add-on](https://pocketpages.dev/docs/plugins/datastar), for requests that carry `Datastar-Request: true`. To serve HTML fragments without the site layout, call `ctx.res.layout(false)`, put the layout in a group (`(site)/+layout.ejs`) and the fragments outside it, or send them with `ctx.res.html()`. --- Source: https://pocketpages.dev/docs/private-files # Working with Private Files and Directories ## Names that are never routed | Prefix | Meaning | |---|---| | `+` | Framework file (`+layout.ejs`, `+page.js`, ...) | | `_` | Private. `_private/` folders hold partials and modules. Other `_` names are ignored. | | `-` | Ignored (drafts, notes) | | `.` | Ignored (dotfiles) | ``` pb_pages/ _private/ # private (not routable) -drafts/ # ignored helpers/ # normal folder (routable) +page.js # framework file (not routable) +layout.ejs # framework file (not routable) index.ejs # page ``` ## The `_private` folder `_private/` folders serve two purposes: 1. Template partials, rendered with [`include()`](https://pocketpages.dev/docs/partials) 2. JavaScript modules and other files, loaded with [`ctx.resolve()`](https://pocketpages.dev/docs/ctx/resolve) Both use the same lookup: `_private/` in the current template's folder, then each parent folder up to `pb_pages/`. A name starting with `/` looks only in `pb_pages/_private/`. ``` pb_pages/ _private/ header.ejs format.js products/ _private/ product-card.ejs queries.js index.ejs ``` ```ejs <% const queries = ctx.resolve('queries') // products/_private/queries.js const format = ctx.resolve('format') // _private/format.js %> <%- include('header') %> <% for (const p of queries.featured(ctx.app)) { %> <%- include('product-card', { p, format }) %> <% } %> ``` ## Modules A module in `_private/` is a CommonJS file: ```js // pb_pages/products/_private/queries.js module.exports = { featured: (app) => app.findRecordsByFilter('products', 'featured = true', '-created', 10), } ``` ## Notes 1. Files in `_private/` are never served. 2. Keep secrets in environment variables (see [Managing Secrets](https://pocketpages.dev/docs/secrets)), not in files. 3. Keep private files close to where they're used, and hoist them up when several sections share them. --- Source: https://pocketpages.dev/docs/middleware # Middleware Middleware files (`+middleware.js`) run before your handlers and templates. Use them to: - Check authentication - Load data a whole section shares - Set headers - Validate requests ## Basic example ```js // pb_pages/admin/+middleware.js module.exports = (ctx, next) => { if (!ctx.auth) return ctx.res.redirect('/login') ctx.data.section = 'admin' return next() } ``` - One signature: `(ctx, next)`. Call `next()` to continue, and return its result. - Returning without calling `next()` ends the request. If no response was sent, that's an error (a `500`; in dev mode the error page names the middleware file). - Share data through `ctx.data`. ## Order Every `+middleware.js` from `pb_pages/` down to the route's folder runs, root first. Groups count too. ``` pb_pages/ +middleware.js # runs first (all routes) products/ +middleware.js # runs second (/products/...) [id]/ +middleware.js # runs third (/products/[id]) ``` The full order for a request is: 1. Plugins' `onRequest` 2. Middleware, root first 3. The folder's `+page.js` or `+api.js` (`load`, then the method's handler) 4. The template, then layouts, innermost first 5. The response If any step sends a response, the later steps are skipped. ## Common uses ### Auth guard ```js module.exports = (ctx, next) => { if (!ctx.auth) return ctx.res.redirect('/login') return next() } ``` ### Request validation ```js // pb_pages/products/[id]/+middleware.js module.exports = (ctx, next) => { if (!/^[a-z0-9]+$/.test(ctx.params.id)) throw ctx.httpError(400, 'Invalid ID') return next() } ``` ### Shared data ```js // pb_pages/+middleware.js module.exports = (ctx, next) => { ctx.data.categories = ctx.app.findRecordsByFilter('categories', 'active = true', 'name', 100) return next() } ``` ```ejs ``` ### Headers ```js module.exports = (ctx, next) => { ctx.res.header('X-Frame-Options', 'DENY') return next() } ``` --- Source: https://pocketpages.dev/docs/asset-management # Asset Management Static files in `pb_pages` (images, CSS, JS, fonts) can be served with fingerprinted URLs that change when the file changes. ## Where to put assets Anywhere in `pb_pages`, next to the pages that use them or in a shared folder: ``` pb_pages/ assets/ app.css logo.png feature/ index.md header.jpg ``` ## In templates Use `asset()` (the same as `ctx.asset()`): ```ejs ``` `asset('/assets/app.css')` returns something like `/assets/app.3f9a1c2b7d4e.css`. - Relative paths resolve from the current file's folder; `/`-paths from `pb_pages`. - A path that isn't a file in `pb_pages` is returned unchanged. ## In Markdown Relative image paths go through `asset()` automatically: ```markdown ![Header](header.jpg) ``` ## How it works 1. A fingerprinted name carries the first 12 hex characters of the file's SHA-256: `name..ext`. 2. Fingerprinted URLs are served with `Cache-Control: public, max-age=31536000, immutable`. 3. When the file changes, its hash and URL change, so browsers and CDNs fetch the new one. See [asset](https://pocketpages.dev/docs/ctx/asset) and [Caching](https://pocketpages.dev/docs/caching). --- Source: https://pocketpages.dev/docs/static-content # Serving Static Content in PocketPages Any file in `pb_pages` that isn't a page (`.ejs`, `.md`, `.jsx`, `.tsx`), a framework file (`+...`), private (`_...`) or ignored (names starting with `-` or `.`) is a static file. It's served as-is at its path, with groups removed: ``` pb_pages/ assets/ app.css -> /assets/app.css logo.png -> /assets/logo.png documents/ terms.pdf -> /documents/terms.pdf (marketing)/ brochure.pdf -> /brochure.pdf favicon.ico -> /favicon.ico index.ejs -> / (a page, not static) ``` - The content type comes from the extension. - The `ETag` comes from the content hash; a matching `If-None-Match` gets `304`. - A static file and a page can't claim the same URL (startup error). For cache-friendly URLs, reference files through [`asset()`](https://pocketpages.dev/docs/asset-management). ## `pb_pages` and `pb_public` A URL nothing in `pb_pages` matches goes on to `pb_public`, so you can keep using `pb_public` for files you don't want next to your pages. --- Source: https://pocketpages.dev/docs/secrets # Managing Secrets in PocketPages Keep API keys, passwords and other secrets in environment variables, and read them with `ctx.env(name)`. It returns `''` when the variable is unset. ```js // pb_pages/checkout/+page.js module.exports = { post(ctx) { const key = ctx.env('STRIPE_SECRET_KEY') if (!key) throw new Error('STRIPE_SECRET_KEY is not set') // ... }, } ``` `ctx.env` reads the app's environment. Under a multitenant host's sandbox, it reads the instance's environment. ## Best practices 1. **Never put secrets in the page.** Anything a template outputs goes to the browser. ```ejs ``` 2. **Check for required variables** and fail clearly when one is missing. 3. **Use descriptive names**: `STRIPE_SECRET_KEY`, not `KEY`. 4. **Never commit secrets** to version control, and use different values in development and production. ## Setting environment variables ```bash # Shell export STRIPE_SECRET_KEY=sk_test_... pocketone serve ``` ```dockerfile # Docker ENV STRIPE_SECRET_KEY=sk_test_... ``` --- Source: https://pocketpages.dev/docs/config # Configuration with `+config.js` Create `pb_pages/+config.js` to configure PocketPages for the app. It's only allowed at the top of `pb_pages`; a `+config.js` in a subfolder is an error at startup. ```js // pb_pages/+config.js module.exports = { plugins: ['auth', 'realtime', 'datastar'], debug: false, } ``` ## Options | Key | Default | | |---|---|---| | `plugins` | `[]` | Built-in plugins by name, or JS plugin factories. EJS and Markdown are always on. | | `debug` | `false` | Detailed error pages and `ctx.log.debug` output even outside dev mode. | `+config.js` must export an object; exporting a function (0.x's `(api) => ({...})` form) is an error. `+config.js` runs on each page request, so these aren't caught at startup: unknown keys, names that are neither a module nor a built-in, or a plugin listed twice make every page answer with an error (a 500; dev mode shows the reason on the page), and the reason goes to the log. ## Plugins Each entry in `plugins` is one of: - **A name**, loaded with `require`: a `_private/` file (`'datastar'` for the [Datastar add-on](https://pocketpages.dev/docs/plugins/datastar)), then a package in `node_modules`, then a built-in (`'auth'` or `'realtime'`). It must export a plugin factory. See [Plugins](https://pocketpages.dev/docs/plugins). - **A JS plugin factory**: a function that returns hooks, such as `require('./_private/my-plugin.js')`. A `require` with a path loads exactly that file, skipping the name lookup, so it's how you choose one copy over another. - **An object with a factory and options**: `{ factory, ...options }`. The object is passed to the factory as its `config`. ```js module.exports = { plugins: [ 'auth', 'realtime', { factory: require('./_private/banner.js'), text: 'Hello' }, ], } ``` Plugin hooks run in the order the plugins are listed. See [Plugin Authoring](https://pocketpages.dev/docs/plugins/authoring). ## Debug `debug: true` turns on what dev mode (`--dev`) turns on: detailed error pages and `ctx.log.debug` output. See [Debugging](https://pocketpages.dev/docs/debugging). --- Source: https://pocketpages.dev/docs/caching # Understanding Caching in PocketPages ## Fingerprinted assets `asset()` adds a content hash to a file's URL: ```ejs ``` - The hash is the first 12 hex characters of the file's SHA-256. - Fingerprinted URLs are served with `Cache-Control: public, max-age=31536000, immutable`, so browsers and CDNs keep them for a year. - When the file changes, the hash changes, and so does the URL. Old copies are never served for the new URL. - A path that isn't a file in `pb_pages` is returned unchanged (and not fingerprinted). ## Static files Every static file gets an `ETag` from its content hash. A request with a matching `If-None-Match` gets `304 Not Modified`. ## Templates A template is compiled once per content hash and reused. Edit a file and the next request uses the new version, in every mode. ## Routes The route table is built at startup and rebuilt whenever anything in `pb_pages` changes. A rebuild never restarts the app. ## Pages Rendered pages aren't cached. To let browsers or a CDN cache a page, set a header in a handler or middleware: ```js module.exports = (ctx, next) => { ctx.res.header('Cache-Control', 'public, max-age=60') return next() } ``` --- Source: https://pocketpages.dev/docs/errors # Errors ## Thrown errors Anything thrown in middleware, a handler or a template becomes a `500`. - **Dev mode or `debug: true`:** an HTML error page with the message, the file and line (template lines map to the `.ejs` or `.md` source), and the stack trimmed to `pb_pages`-relative paths. - **Otherwise:** a plain "Something went wrong" page. The full error always goes to the app's log. ## `ctx.httpError(status, message)` Throw `ctx.httpError()` to answer with a specific status: ```js // pb_pages/products/[id]/+page.js module.exports = { load(ctx) { let product try { product = ctx.app.findFirstRecordByData('products', 'slug', ctx.params.id) } catch (e) { throw ctx.httpError(404, 'No such product') // findFirstRecordByData throws when nothing matches } ctx.data.product = product }, } ``` - In a page, it sends that status with a plain page showing `message`. - In a `+api.js`, it sends JSON: `{ "status": 404, "message": "No such product" }`. ## A custom error page Create `pb_pages/+error.ejs`. It renders for every `ctx.httpError` and for every `500` outside dev mode, inside the root layout, with `ctx.error = { status, message }`: ```ejs <% slot('title', () => { %>Error <%= ctx.error.status %><% }) %>

<%= ctx.error.status %>

<%= ctx.error.message %>

``` `+error` and `+404` live only at the top of `pb_pages`. Either may be `.ejs`, `.jsx` or `.tsx`. ## A custom 404 page Create `pb_pages/+404.ejs`. It renders inside the root layout, with status `404`, for a `GET` or `HEAD` that nothing answers: no page, no file in `pb_public` and no PocketBase route. It never renders for `/api/` or `/_/`. The root `+middleware.js` runs first, and page code can still change the status. ```ejs <% slot('title', () => { %>Not found<% }) %>

Not found

Nothing lives at <%= ctx.req.url.pathname %>.

``` --- Source: https://pocketpages.dev/docs/debugging # Debugging in PocketPages ## Dev mode Run `pocketone` with `--dev`: ```bash pocketone serve --dev ``` Dev mode turns on: - detailed error pages (message, file and line, trimmed stack; see [Errors](https://pocketpages.dev/docs/errors)); - `ctx.log.debug` output. ## `debug: true` To get the same in production, set `debug: true` in `+config.js`: ```js module.exports = { debug: true, } ``` Turn it off again when you're done. Detailed error pages show error messages, file paths and stack traces to anyone who triggers an error. ## Logging `ctx.log` writes to the app's log: ```js ctx.log.debug('loaded product', ctx.params.id) // only in dev mode or with debug: true ctx.log.info('order placed') ctx.log.warn('stock is low') ctx.log.error('payment failed') ``` See [log](https://pocketpages.dev/docs/ctx/log). ## Template changes Templates are cached by content hash and the route table is rebuilt on any file change, in every mode. If a change doesn't show, check the app's log for a startup error (bad file name, route conflict): the previous route table keeps serving until the error is fixed. --- Source: https://pocketpages.dev/docs/deploying # Going Live A PocketPages app is a `pb_pages` folder. To go live, run PocketOne on your server (pages is built in) and put `pb_pages` next to `pb_data`, along with your other `pb_*` folders: ``` pb_data/ pb_hooks/ pb_migrations/ pb_public/ pb_pages/ ``` Or point `pocketone` at it with `--pagesDir`. ## Updating Copy the changed files into `pb_pages`. The route table is rebuilt on any change, and templates are cached by content hash, so updates show on the next request without restarting the app. If an update has a startup error (a bad name or a route conflict), it's logged with the file path and the previous route table keeps serving. ## Before you go live - Run without `--dev`, and keep `debug: false` in `+config.js`. - Set secrets as environment variables (see [Managing Secrets](https://pocketpages.dev/docs/secrets)). - Serve over HTTPS. Cookies set with `ctx.res.cookie` are marked `Secure` on HTTPS requests. ## Multitenant hosts Under a multitenant PocketOne host, every instance has its own `pb_pages`, and page code runs with the same limits as the rest of the instance's JS. --- Source: https://pocketpages.dev/docs/plugins # Plugins Plugins add features to `ctx` and hook into each request. Turn them on in `+config.js`: ```js // pb_pages/+config.js module.exports = { plugins: ['auth', 'realtime', 'datastar'], } ``` Each entry is one of: - **A name in quotes.** It's loaded with `require`, which looks in this order: 1. a `_private/` folder in `pb_pages` (`'datastar'` finds `_private/datastar.js`) 2. `pb_pages/node_modules`, for a package from your `package.json` 3. the built-in plugins, `'auth'` and `'realtime'` A path such as `'./plugins/my-plugin.js'` works too. - **A plugin factory**, usually `require('./_private/my-plugin.js')`. Writing the `require` yourself with a path skips the lookup above and loads exactly that file, which is how you pick one copy over another: `'datastar'` would find `_private/datastar.js` first, while `require('./node_modules/datastar')` always loads the package. Datastar isn't built in. It's an add-on file you copy into `pb_pages/_private/` and list by name. EJS and Markdown are always on; they aren't plugins. ## Built-in plugins | Name | Adds | |---|---| | [`auth`](https://pocketpages.dev/docs/plugins/auth) | Cookie sessions on PocketBase auth: sets `ctx.auth` from the `pb_auth` cookie and adds `ctx.session.*` sign-in methods. | | [`realtime`](https://pocketpages.dev/docs/plugins/realtime) | `ctx.realtime.send()` to PocketBase realtime subscribers. | ## JS plugins A JS plugin is a module that exports a factory returning hooks. List it by name, or `require()` it yourself, which you need for options (`{ factory, ...options }`): ```js module.exports = { plugins: ['auth', 'my-plugin', { factory: require('./_private/other-plugin.js'), color: 'blue' }], } ``` See [Plugin Authoring](https://pocketpages.dev/docs/plugins/authoring). | Add-on | Adds | |---|---| | [Datastar](https://pocketpages.dev/docs/plugins/datastar) | `ctx.datastar.*` helpers for [Datastar](https://data-star.dev). Copy [`addons/datastar.js`](https://github.com/pockethost/pocketone/blob/main/ext/pages/addons/datastar.js) into `pb_pages/_private/`; the `datastar` starter kit already has it. | ## Order Plugins' hooks run in the order they're listed, and `onRequest` hooks run before any middleware. --- Source: https://pocketpages.dev/docs/plugins/auth # Authentication Plugin The `auth` plugin gives you cookie sessions on PocketBase auth. It calls the app directly, not over HTTP. ```js // pb_pages/+config.js module.exports = { plugins: ['auth'], } ``` ## What it does on every request It reads the `pb_auth` cookie, validates the token and sets `ctx.auth` to the authenticated record. A bad cookie is cleared. `ctx.auth` is also set without the plugin when a request carries PocketBase's own `Authorization` header. ## `ctx.session` | Method | | |---|---| | `register(email, password, { collection = 'users', data, verify = true, signIn = true }?)` | Create an auth record. `data` holds extra fields. `verify` sends the verification email; `signIn` signs the new account in (returns `{ token: '', record }` when `false`). | | `signInWithPassword(email, password, { collection }?)` | Sign in with a password. | | `requestOTP(email, { collection, create = false }?)` | Send a one-time password. Returns the `otpId`. An unknown email still gets an id, one that never validates; with `create: true` the account is created first. | | `signInWithOTP(otpId, code, { collection }?)` | Sign in with a one-time password. | | `signInAnonymously({ collection }?)` | Sign in as a new anonymous user. | | `requestOAuth2(provider, { collection, redirectPath = '/auth/oauth/confirm', redirect = true }?)` | Store state in a cookie and return the provider's URL. With `redirect` it also sends the redirect; pass `redirect: false` to send the URL some other way. `redirectPath` must be a path on this site. | | `signInWithOAuth2(state, code, { createData }?)` | Complete an OAuth2 sign-in on the redirect path. Returns `{ token, record, meta }`; `meta.isNew` is `true` for a new account. | | `signIn(record)` | Set the cookie for a record you authenticated yourself. It skips the MFA check below. | | `signOut()` | Sign out. | | `authMethods({ collection }?)` | The sign-in methods a collection has turned on: `{ password: { enabled, identityFields }, otp: { enabled }, mfa: { enabled }, oauth2: { enabled, providers: [{ name, displayName }] } }`, as PocketBase's auth-methods API. | ### MFA Pages doesn't have a second sign-in step yet. If a collection has MFA turned on (Collections → `users` → Options → Multi-factor authentication) and its MFA rule matches the account, every sign-in method above refuses it with "This account needs a second sign-in step (MFA), which pages doesn't support yet." An empty rule matches every account. To use pages sign-in, turn MFA off for the collection, or give it a rule that leaves out the accounts that sign in here. Every sign-in method sets `ctx.auth` for the rest of the request and returns `{ token, record }`. ### Email flows These use PocketBase's own checks and mail templates. The request methods never reveal whether an email exists. | Method | | |---|---| | `requestVerification(email, { collection }?)` | Send the verification email (skipped for an account that's already verified). | | `confirmVerification(token)` | Mark the account verified. Returns the record. | | `requestPasswordReset(email, { collection }?)` | Send the password reset email. | | `confirmPasswordReset(token, password, passwordConfirm)` | Set the new password (and mark the account verified). Returns the record. | | `requestEmailChange(newEmail)` | Send a confirmation email to `newEmail`. Needs a signed-in user (`ctx.auth`). | | `confirmEmailChange(token, password)` | Change the email after checking the current password. Returns the record. | A bad or expired token throws an error. ## Example ```js // pb_pages/login/+page.js module.exports = { post(ctx) { const { email, password } = ctx.req.body() try { ctx.session.signInWithPassword(email, password) } catch (e) { return { error: 'Invalid email or password', email } } return ctx.res.redirect('/') }, } ``` ```js // pb_pages/logout/+page.js module.exports = { post(ctx) { ctx.session.signOut() return ctx.res.redirect('/') }, } ``` See the [Authentication guide](https://pocketpages.dev/docs/authentication) for complete flows: registration, one-time passwords, OAuth2 and anonymous sign-in. --- Source: https://pocketpages.dev/docs/plugins/datastar # Datastar Add-on The Datastar add-on adds helpers for [Datastar](https://data-star.dev). It's a JS plugin that ships with PocketPages rather than a built-in: copy [`addons/datastar.js`](https://github.com/pockethost/pocketone/blob/main/ext/pages/addons/datastar.js) into `pb_pages/_private/` (the `datastar` starter kit already has it) and list it in `+config.js` by name: ```js // pb_pages/+config.js module.exports = { plugins: ['datastar'], } ``` Add the script tags to your root layout's ``. They load [Datastar](https://data-star.dev) v1.0.5. Datastar 1.0 uses a colon between the attribute name and its key (`data-on:click`, `data-bind:name`, `data-signals:count`, `data-class:active`, `data-attr:href`); the older hyphen form (`data-on-click`) is ignored. See the [Datastar attribute reference](https://data-star.dev/reference/attributes). ```ejs <%- ctx.datastar.scripts() %> ``` ## `ctx.datastar` | Member | | |---|---| | `scripts({ spa, realtime }?)` | Returns the script tags. | | `patchElements(html, { selector, mode, useViewTransition, viewTransitionSelector, namespace }?)` | Sends a patch-elements SSE event on the current response. `mode` is `outer` (default), `inner`, `replace`, `prepend`, `append`, `before`, `after` or `remove`; `namespace` is `html` (default), `svg` or `mathml`. | | `patchSignals(signals, { onlyIfMissing }?)` | Sends a patch-signals SSE event (JSON Merge Patch: `null` removes a signal). | | `executeScript(js, { autoRemove, attributes }?)` | Sends a script to run in the browser. | | `consoleLog(msg)` / `consoleError(err)` | Logs to the browser console. | | `redirect(url)` | Sends the browser to `url` (a full page load). A Datastar fetch can't follow `ctx.res.redirect`, so use this from `@get`/`@post` handlers. | | `dispatchCustomEvent(name, detail, { selector }?)` | Fires a `CustomEvent` on `document`, or on the elements matching `selector`. | | `replaceURL(url)` | Changes the address bar without a navigation (`history.replaceState`). | | `prefetch(urls)` | Adds speculation rules so the browser prefetches `urls`. | | `signals()` | Reads the request's signals as an object: from the `datastar` query parameter for GET and DELETE, from the body otherwise. | | `readSignals(target)` | Merges the request's signals into `target` and returns it (0.x's `readSignals(request, target)` also works). | | `realtime.*` | Sends the same patches to realtime subscribers. Needs the [`realtime`](https://pocketpages.dev/docs/plugins/realtime) plugin. | Every send also takes `eventId` and `retryDuration` (in ms; the default 1000 isn't sent). ## Pages as patches When a request has the `Datastar-Request: true` header, the rendered page is sent without layouts, as a `patchElements` event. If the request has a `Datastar-Selector` header, the patch goes into that element. This is how this site navigates between docs pages: the layout calls ```ejs <%- ctx.datastar.scripts({ spa: { scope: '#toc', selector: '#content' } }) %> ``` so links in the table of contents fetch the page and patch it into `#content`. Plain left-clicks are intercepted; modified clicks (Cmd/Ctrl/Shift/Alt, middle-click), links with a `target` attribute and links to other origins navigate normally. Back/Forward work, including back to the page you landed on: each page opens at the top, and Back/Forward return you to where you were scrolled. ## Example: a counter ```ejs ``` ```js // pb_pages/counter/+page.js module.exports = { post(ctx) { const count = (ctx.store('count') || 0) + 1 ctx.store('count', count) ctx.datastar.patchElements(`${count}`) }, } ``` ## Example: reading signals ```js module.exports = { post(ctx) { const { name, email } = ctx.datastar.signals() if (!name || !email) { ctx.datastar.patchSignals({ error: 'Please fill all fields' }) return } ctx.datastar.patchElements('
Thanks!
') }, } ``` ## Broadcasting With the `realtime` plugin on, `ctx.datastar.realtime.*` sends patches to every realtime subscriber instead of the current response: ```js // pb_pages/+config.js module.exports = { plugins: ['realtime', 'datastar'] } ``` ```js ctx.datastar.realtime.patchElements(`${count}`) ``` --- Source: https://pocketpages.dev/docs/plugins/realtime # Realtime Plugin The `realtime` plugin sends messages to [PocketBase realtime](https://pocketbase.io/docs/realtime/) subscribers. ```js // pb_pages/+config.js module.exports = { plugins: ['realtime'], } ``` ## `ctx.realtime.send(topic, data, { filter }?)` Sends `data` to the subscribers of `topic`. `filter(client)` may limit the recipients. ```js // pb_pages/ping/+api.js module.exports = { post(ctx) { ctx.realtime.send('ping', { at: new Date().toISOString() }) return ctx.res.json({ ok: true }) }, } ``` On the client, subscribe with the PocketBase JS SDK: ```html ``` ## Filtering recipients ```js ctx.realtime.send('alerts', 'Maintenance at 10:00', { filter: (client) => !!client.get('auth'), }) ``` ## Sending HTML For hypermedia libraries (HTMX, Datastar), send rendered HTML. `include()` is available in templates, so render the partial there: ```js // pb_pages/xapi/chat/+page.js module.exports = { post() {}, // accept POST; the page renders and sends } ``` ```ejs <% ctx.realtime.send('chat', include('chat-msg', { message: ctx.req.body().message })) %> ``` See [Realtime Events](https://pocketpages.dev/docs/realtime) and the [Datastar add-on](https://pocketpages.dev/docs/plugins/datastar), which can send Datastar patches over realtime. --- Source: https://pocketpages.dev/docs/plugins/authoring # Plugin Authoring Guide A JS plugin is a factory that returns hooks: ```js // pb_pages/_private/my-plugin.js module.exports = (config) => ({ name: 'my-plugin', onRequest(ctx) {}, // before middleware extendContext(ctx) { ctx.hello = () => 'hi' }, transform({ html, ctx, file }) { return html }, // after each template or layout renders }) ``` Turn it on in `+config.js`: ```js module.exports = { plugins: ['my-plugin'], // pb_pages/_private/my-plugin.js } ``` ## `config` `config` is the plugin's entry in `+config.js` when that entry is an object (`{ factory, ...options }`), else `{}`: ```js module.exports = { plugins: [{ factory: require('./_private/banner.js'), text: 'Beta' }], } ``` ```js // pb_pages/_private/banner.js module.exports = (config) => ({ name: 'banner', transform({ html }) { return html.replace('', ``) }, }) ``` ## Hooks Every hook is optional. Hooks run in the order plugins are listed in `+config.js`. | Hook | When | |---|---| | `name` | The plugin's name. | | `onRequest(ctx)` | At the start of each request, before middleware. | | `extendContext(ctx)` | Add members to `ctx`. | | `transform({ html, ctx, file })` | After each template or layout renders. Return the new HTML. | ## Example: a context helper ```js module.exports = () => ({ name: 'format', extendContext(ctx) { ctx.formatDate = (d) => new Date(d).toLocaleDateString() }, }) ``` ```ejs

Posted <%= ctx.formatDate(data.post.getString('created')) %>

``` ## Permissions JS plugins run with the same permissions as the rest of the app's JS. Under a multitenant host, that means the instance's sandbox. --- Source: https://pocketpages.dev/docs/ctx # The `ctx` Object PocketPages creates one `ctx` object per request and passes it to middleware, handlers, templates and plugins. ```js // +middleware.js module.exports = (ctx, next) => next() // +page.js / +api.js module.exports = { load(ctx) {} } ``` ```ejs

<%= ctx.req.url.pathname %>

``` In templates, `data`, `params`, `asset` and `meta` are shortcuts for `ctx.data`, `ctx.params`, `ctx.asset` and `ctx.meta`. ## Members | Member | | |---|---| | [`ctx.req`](https://pocketpages.dev/docs/ctx/req) | The request: method, URL, query, headers, cookies, body, files | | [`ctx.res`](https://pocketpages.dev/docs/ctx/res) | The response: status, headers, cookies, redirects, JSON, HTML, text, files, SSE | | [`ctx.data`](https://pocketpages.dev/docs/ctx/data) | Plain object shared by middleware, handlers and templates | | [`ctx.params`](https://pocketpages.dev/docs/ctx/data#ctxparams) | Route parameters | | [`ctx.route`](https://pocketpages.dev/docs/ctx/data#ctxroute) | The matched route: `{ path, name, file }` | | [`ctx.flash()`](https://pocketpages.dev/docs/ctx/flash) | The one-time message from the previous redirect | | [`ctx.auth`](https://pocketpages.dev/docs/ctx/auth) | The authenticated record, or `null` | | [`ctx.app`](https://pocketpages.dev/docs/ctx/app) | The app (`$app`) | | [`ctx.pb()`](https://pocketpages.dev/docs/ctx/pb) | A JS SDK client acting as the visitor (API rules apply) | | [`ctx.env(name)`](https://pocketpages.dev/docs/ctx/env) | Environment variable | | [`ctx.log`](https://pocketpages.dev/docs/ctx/log) | `debug`, `info`, `warn`, `error` | | [`ctx.meta(key, value?)`](https://pocketpages.dev/docs/ctx/meta) | Per-request page metadata | | [`ctx.asset(path)`](https://pocketpages.dev/docs/ctx/asset) | Fingerprinted URL for a static file | | [`ctx.include(name, locals?)`](https://pocketpages.dev/docs/partials) | Render a `_private/` partial from JS and get its text (same lookup as `include`, from the route's folder) | | [`ctx.resolve(name, { mode }?)`](https://pocketpages.dev/docs/ctx/resolve) | Load a module from `_private/` | | [`ctx.store(name, value?)`](https://pocketpages.dev/docs/ctx/store) | The app's in-memory store | | `ctx.pagesDir` | Absolute path of the app's `pb_pages` folder (read-only), e.g. for `$os.readDir` | | `ctx.dev` | `true` in dev mode | | [`ctx.httpError(status, message)`](https://pocketpages.dev/docs/errors) | An error to throw for a specific status | | [`ctx.error`](https://pocketpages.dev/docs/errors) | `{ status, message }`, in `+error.ejs` | ## Added by plugins | Member | Plugin | |---|---| | `ctx.session` | [auth](https://pocketpages.dev/docs/plugins/auth) | | `ctx.realtime` | [realtime](https://pocketpages.dev/docs/plugins/realtime) | | `ctx.datastar` | [datastar](https://pocketpages.dev/docs/plugins/datastar) | JS plugins can add their own members with [`extendContext`](https://pocketpages.dev/docs/plugins/authoring). --- Source: https://pocketpages.dev/docs/ctx/req # `ctx.req` | Member | | |---|---| | `method` | `"GET"`, `"POST"`, ... | | `url` | `{ href, origin, pathname, search }` | | `query(name)` | First value of a query parameter as a string, or `undefined` | | `query(name, { all: true })` | Every value, as an array of strings | | `query()` | `{ name: firstValue }` for every parameter | | `header(name)` | Request header, `''` if absent | | `cookie(name)` | Cookie value as a string, or `undefined` | | `cookie(name, { json: true })` | Cookie parsed as JSON (`undefined` if absent or not JSON) | | `cookies()` | `{ name: value }`, strings | | `body()` | Parsed body: a JSON object, or form fields as `{ name: value }` (repeated names as arrays) | | `files(name)` | Uploaded files for a multipart field, as PocketBase `*filesystem.File` values ready for a record field | | `ip` | Client IP as PocketBase resolves it (trusted proxy settings apply) | | `event` | The underlying PocketBase `RequestEvent`, for anything not covered here | Query values and cookies are strings unless you ask for JSON. Nothing is parsed for you. ## Examples ```ejs

You asked for <%= ctx.req.url.pathname %><%= ctx.req.url.search %>

Page <%= Number(ctx.req.query('page') ?? 1) %>

Browser: <%= ctx.req.header('User-Agent') %>

``` ### Forms `body()` parses JSON, `application/x-www-form-urlencoded` and `multipart/form-data`: ```js // pb_pages/contact/+page.js module.exports = { post(ctx) { const { email, message } = ctx.req.body() // ... }, } ``` ### File uploads ```html
``` ```js module.exports = { post(ctx) { const record = ctx.app.findRecordById('users', ctx.auth.id) record.set('avatar', ctx.req.files('avatar')[0]) ctx.app.save(record) return ctx.res.redirect('/account') }, } ``` ### Cookies ```js const theme = ctx.req.cookie('theme') // 'dark' or undefined const prefs = ctx.req.cookie('prefs', { json: true }) ?? {} ``` Set cookies with [`ctx.res.cookie()`](https://pocketpages.dev/docs/ctx/res#cookies). --- Source: https://pocketpages.dev/docs/ctx/res # `ctx.res` | Member | | |---|---| | `status(code)` | Status for the rendered page. Returns `ctx.res`. | | `header(name, value)` | Set a response header. `header(name)` reads it back. | | `cookie(name, value, options?)` | Set a cookie. | | `clearCookie(name, options?)` | Expire a cookie (same `path` / `domain` as when set). | | `redirect(location, { status = 302, flash }?)` or `redirect(location, status)` | Send a redirect. `status` must be a 3xx code. `flash` sets a [one-time message](https://pocketpages.dev/docs/ctx/flash). | | `json(data)` / `json(status, data)` | Send JSON. | | `html(html)` / `html(status, html)` | Send HTML as-is (no layouts). | | `text(text)` / `text(status, text)` | Send plain text. | | `file(path)` | Send a file from `pb_pages` (path relative to `pb_pages`). | | `sse()` | Start a `text/event-stream` response. | | `layout(false)` | Render this page without layouts (e.g. an HTML fragment for htmx). Returns `ctx.res`. | | `sent` | `true` once a response has been sent. | Once a response is sent, the later steps of the request (handlers, template, layouts) are skipped. ## Status and headers ```ejs <% ctx.res.status(404).header('Cache-Control', 'no-store') %>

Not here

``` ## Redirects ```js return ctx.res.redirect('/login') return ctx.res.redirect('/account', { flash: 'Saved' }) return ctx.res.redirect('/new-home', 301) // or { status: 301 } ``` ## Cookies ```js ctx.res.cookie('theme', 'dark', { maxAge: 60 * 60 * 24 * 365 }) ctx.res.cookie('prefs', { compact: true }) // objects are JSON.stringify'd ctx.res.clearCookie('theme') ``` - Non-string values are `JSON.stringify`'d. The value is then percent-encoded (`encodeURIComponent`), and `ctx.req.cookie` decodes it. - Defaults: `path=/`, `HttpOnly`, `SameSite=Lax`, and `Secure` when the request is HTTPS. - Options: `path`, `domain`, `maxAge` (seconds), `expires` (a `Date`, milliseconds since the epoch, or a date string; with `maxAge` too, browsers use `maxAge`), `httpOnly`, `secure`, `sameSite`. ## JSON, HTML, text and files ```js return ctx.res.json({ ok: true }) return ctx.res.json(201, { id: record.id }) return ctx.res.html('

Fragment

') return ctx.res.text(404, 'Not found') return ctx.res.file('downloads/manual.pdf') ``` ## Server-sent events `sse()` starts a `text/event-stream` response and returns `{ send(event, data, { id, retry }?), comment(text), close() }`: ```js // pb_pages/clock/+api.js module.exports = { get(ctx) { const stream = ctx.res.sse() stream.send('time', new Date().toISOString()) stream.close() }, } ``` Streaming is only available through `sse()`. Templates return their text all at once. --- Source: https://pocketpages.dev/docs/ctx/data # `ctx.data`, `ctx.params`, `ctx.route` ## `ctx.data` A plain object shared by middleware, handlers and templates. It starts as `{}`. In templates it's also available as `data`. ```js // +middleware.js module.exports = (ctx, next) => { ctx.data.user = ctx.auth return next() } ``` ```js // +page.js module.exports = { load(ctx) { return { products: ctx.app.findAllRecords('products') } // Object.assign'd into ctx.data }, } ``` ```ejs <% for (const p of data.products) { %>
  • <%= p.getString('name') %>
  • <% } %> ``` A handler's returned object is shallow-assigned into `ctx.data`. There is no deep merge. ## `ctx.params` Route parameters from `[name]` segments, as strings. Never includes query parameters (use [`ctx.req.query()`](https://pocketpages.dev/docs/ctx/req)). In templates it's also available as `params`. ```ejs

    <%= params.org %>/<%= params.repo %>

    ``` ## `ctx.route` `{ path, name, file }`: the route pattern, the page name and its file relative to `pb_pages`. | Page file | `path` | `name` | |---|---|---| | `products/[id].ejs` | `/products/[id]` | `[id]` | | `docs/index.md` | `/docs` | `index` | A `+page.js` applies to every page in its folder; use `ctx.route.name` to tell them apart. --- Source: https://pocketpages.dev/docs/ctx/flash # `ctx.flash()` A flash is a one-time message that survives one redirect, such as "Saved" after a form post. ## Setting a flash ```js return ctx.res.redirect('/account', { flash: 'Saved' }) ``` The message is stored as JSON in a cookie (`pp_flash`, `HttpOnly`, `Max-Age=300`). It can be any JSON value: ```js return ctx.res.redirect('/cart', { flash: { type: 'success', text: 'Added to cart' } }) ``` ## Reading it On the next request, `ctx.flash()` returns the message and clears the cookie. It returns `undefined` when there is none. Calling it again in the same request returns the same value. ```ejs <% const flash = ctx.flash() %> <% if (flash) { %>
    <%= flash.text %>
    <% } %> ``` Read it in your layout to show flashes on every page. --- Source: https://pocketpages.dev/docs/ctx/auth # `ctx.auth` The authenticated record, or `null`. It's set by: - PocketBase's own auth, when the request has an `Authorization` header; - the [`auth` plugin](https://pocketpages.dev/docs/plugins/auth), from its `pb_auth` cookie. ```ejs <% if (ctx.auth) { %>

    Welcome, <%= ctx.auth.email() %>

    <% if (!ctx.auth.verified()) { %>

    Please verify your email.

    <% } %> <% } else { %> Log in <% } %> ``` `ctx.auth` is a PocketBase record, so the usual record methods work: `get(field)`, `getString(field)`, `email()`, `verified()`, `isSuperuser()`, `collection()`. ## Protecting pages ```js // pb_pages/account/+middleware.js module.exports = (ctx, next) => { if (!ctx.auth) return ctx.res.redirect('/login') return next() } ``` --- Source: https://pocketpages.dev/docs/ctx/app # `ctx.app` The app (`$app`): records, collections, settings. Page code calls it directly, with no HTTP round trip. ```js module.exports = { load(ctx) { return { product: ctx.app.findRecordById('products', ctx.params.id), latest: ctx.app.findRecordsByFilter('posts', 'published = true', '-created', 10), } }, } ``` Everything in PocketBase's [JavaScript records](https://pocketbase.io/docs/js-records/) and [database](https://pocketbase.io/docs/js-database/) docs that uses `$app` works on `ctx.app`. Calls through `ctx.app` don't apply collection API rules: page code is trusted server code. Check `ctx.auth` yourself before reading or changing data on a user's behalf. --- Source: https://pocketpages.dev/docs/ctx/pb # `ctx.pb()`: the JS SDK in page code `ctx.pb()` returns a [PocketBase JS SDK](https://github.com/pocketbase/js-sdk) client, the same API you use in the browser: ```js // pb_pages/posts/+page.js module.exports = { load(ctx) { const page = ctx.pb().collection('posts').getList(1, 20, { filter: 'published = true', sort: '-created', expand: 'author', }) return { posts: page.items } }, } ``` - **It acts as the visitor.** When someone is signed in (`ctx.auth`, for example through the `auth` plugin), the client is authenticated as them; otherwise it's a guest. Your collections' API rules, `expand` and hidden fields apply exactly as they would in the browser. - **It's synchronous.** Calls return their result directly; no `await`. - **No network.** Requests go straight to your app's own API, in-process. There's no host or port to set, and it works the same on any server. - **Errors** throw the SDK's `ClientResponseError`: ```js try { const post = ctx.pb().collection('posts').getOne(ctx.params.id) } catch (e) { if (e.status === 404) throw ctx.httpError(404, 'No such post') throw e } ``` - **Limits:** only `/api/` routes; file uploads through the SDK aren't supported, so use `ctx.app` for those. ## `ctx.pb()` or `ctx.app`? | | `ctx.pb()` | `ctx.app` | |---|---|---| | Permissions | the visitor's: API rules apply | full access, no rules | | API | the JS SDK, same as the browser | PocketBase's JSVM API (`findRecordsByFilter`, `save`, ...) | | Use it for | reading and writing on the visitor's behalf | admin work, background jobs, anything rules shouldn't limit | When in doubt, use `ctx.pb()`: if a page shows something, the visitor is allowed to see it. --- Source: https://pocketpages.dev/docs/ctx/env # `ctx.env(name)` Returns an environment variable, or `''` if it's unset. ```js const key = ctx.env('STRIPE_SECRET_KEY') ``` It reads the app's environment. Under a multitenant host's sandbox, it reads the instance's environment. See [Managing Secrets](https://pocketpages.dev/docs/secrets). --- Source: https://pocketpages.dev/docs/ctx/log # `ctx.log` Writes to the app's log. ```js ctx.log.debug('cart', ctx.data.cart) ctx.log.info('order placed') ctx.log.warn('stock is low') ctx.log.error('payment failed') ``` `debug` only shows in dev mode (`--dev`) or with `debug: true` in `+config.js`. See [Debugging](https://pocketpages.dev/docs/debugging). --- Source: https://pocketpages.dev/docs/ctx/meta # `ctx.meta(key, value?)` A per-request key/value store for page metadata (title, description). Set with two arguments, read with one. In templates it's also available as `meta`. ```ejs <% meta('title', data.product.getString('name')) %> <% meta('description', data.product.getString('summary')) %> ``` ```ejs <%= meta('title') || 'My shop' %> ``` Layouts render after the page, so they see what the page set. ## Front matter In a `.md` page, each top-level key of the YAML front matter is passed to `ctx.meta(key, value)`: ```markdown --- title: About us description: Who we are --- ``` --- Source: https://pocketpages.dev/docs/ctx/asset # `ctx.asset(path)` Returns the URL for a static file in `pb_pages`, with its content hash. In templates it's also available as `asset`. ```ejs ``` - Relative paths resolve from the current file's folder; `/`-paths from `pb_pages`. - A path that isn't a file in `pb_pages` is returned unchanged. - The hash is the first 12 hex characters of the file's SHA-256: `name..ext`. - Fingerprinted URLs are served with `Cache-Control: public, max-age=31536000, immutable`. Relative image paths in Markdown pages go through `ctx.asset` automatically. See [Asset Management](https://pocketpages.dev/docs/asset-management). --- Source: https://pocketpages.dev/docs/ctx/resolve # `ctx.resolve(name, { mode }?)` Loads a module from a `_private/` folder. The lookup starts at the **route's** folder (the page being served), wherever `ctx.resolve` is called from, so a layout or partial gets the same answer as the page: `_private/` in the route's folder, then each parent folder up to `pb_pages/`. A name starting with `/` looks only in `pb_pages/_private/`. Without an extension, the name, then `.js`, `.ts` and `.json` are tried. ```js // pb_pages/_private/shout.js module.exports = (s) => String(s).toUpperCase() ``` ```ejs

    <%= ctx.resolve('shout')('hi') %>

    ``` ## Modes | Mode | Returns | |---|---| | `require` (default) | The module's exports | | `raw` | The file's text | | `script` | The text wrapped in ` ``` ## Route organization HTMX requests want HTML fragments, not whole pages wrapped in your layout. Put the layout in a group, and the fragment routes outside it: ``` pb_pages/ (site)/ # Pages with layouts +layout.ejs # Main site layout index.ejs # / products/ index.ejs # /products xapi/ # HTMX endpoints (no layouts) products/ search.ejs # /xapi/products/search create/ +page.js index.ejs # /xapi/products/create ``` 1. `(site)` holds full pages. Its `+layout.ejs` wraps them, and the group adds nothing to the URL. 2. `xapi/` holds fragments. No layout applies to them, because there is no `+layout.ejs` at the root. Don't name the folder `api/`: `/api/` belongs to PocketBase. A handler can also send a fragment directly with `ctx.res.html()`, which never applies layouts. ## Sharing partials Render the same fragment on the first page load and in HTMX responses by keeping it in a `_private/` partial: ``` pb_pages/ _private/ product-card.ejs # shared partial (site)/ products/ index.ejs # includes the partial xapi/ products/ more.ejs # includes the same partial ``` ```ejs

    <%= product.getString('name') %>

    <%= product.getString('description') %>

    ``` ```ejs <% const products = ctx.app.findRecordsByFilter('products', 'active = true', 'name', 20) %>
    <% for (const product of products) { %> <%- include('product-card', { product }) %> <% } %>
    ``` ```ejs <% const page = Number(ctx.req.query('page') ?? 1) const products = ctx.app.findRecordsByFilter('products', 'active = true', 'name', 20, (page - 1) * 20) %> <% for (const product of products) { %> <%- include('product-card', { product }) %> <% } %> ``` ## Search as you type ```html
    ``` ```ejs <% const products = ctx.app.findRecordsByFilter( 'products', 'name ~ {:q}', 'name', 20, 0, { q: ctx.req.query('q') ?? '' } ) %> <% for (const product of products) { %> <%- include('product-card', { product }) %> <% } %> ``` ## Forms ```html
    ``` ```js // pb_pages/xapi/products/create/+page.js module.exports = { post(ctx) { const { name, description } = ctx.req.body() const product = new Record(ctx.app.findCollectionByNameOrId('products')) product.set('name', name) product.set('description', description) ctx.app.save(product) return { product } }, } ``` ```ejs <%- include('product-card', { product: data.product }) %> ``` ## Out-of-band updates Update more than one element with a single response: ```ejs <%- include('product-card', { product: data.product }) %>
    <%= ctx.app.countRecords('products') %> Products
    ``` ## Polling ```html
    ``` ## Realtime updates With the [`realtime` plugin](https://pocketpages.dev/docs/plugins/realtime), a page can push rendered HTML to every subscriber. A template has `include()`, so render the partial there and send it: ```js // pb_pages/+config.js module.exports = { plugins: ['realtime'] } ``` ```js // pb_pages/xapi/chat/+page.js module.exports = { post() {}, // accept POST; the page below does the work } ``` ```ejs <% ctx.realtime.send('chat', include('chat-msg', { message: ctx.req.body().message })) %> ``` ```html
    ``` In the browser, subscribe to the topic with the PocketBase JS SDK and append what arrives: ```html ``` ## Best practices 1. **Route organization**: keep fragment routes outside the layout group, in a folder like `xapi/`. 2. **Response size**: return only the HTML the swap needs. 3. **Loading states**: use `hx-indicator` to show progress. 4. **Security**: check `ctx.auth` in middleware before changing data, validate input on the server, and debounce triggers like search inputs. --- Source: https://pocketpages.dev/docs/realtime # Realtime Events PocketBase pushes realtime messages to browsers over server-sent events. In PocketPages, page code sends, and browsers receive. ## Sending from a page Turn on the [`realtime` plugin](https://pocketpages.dev/docs/plugins/realtime) and call `ctx.realtime.send()`: ```js // pb_pages/+config.js module.exports = { plugins: ['realtime'] } ``` ```js // pb_pages/rooms/[id]/+api.js module.exports = { post(ctx) { ctx.realtime.send(`rooms/${ctx.params.id}/delta`, ctx.req.body()) return ctx.res.json({ ok: true }) }, } ``` Limit recipients with a filter: ```js ctx.realtime.send('alerts', 'Hi', { filter: (client) => !!client.get('auth') }) ``` Page code can't subscribe to realtime topics itself; it only sends. ## Receiving in the browser Use the [PocketBase JS SDK](https://github.com/pocketbase/js-sdk#realtimeservice): ```js const pb = new PocketBase(location.origin) const unsubscribe = await pb.realtime.subscribe(`rooms/${ROOM_ID}/delta`, (e) => { console.log('Received delta:', e) }) // Later unsubscribe() ``` The SDK reconnects on its own and resubscribes to its topics after a reconnect. ## Hypermedia To push HTML instead of data, see [HTMX Integration](https://pocketpages.dev/docs/htmx#realtime-updates) and the [Datastar add-on](https://pocketpages.dev/docs/plugins/datastar#broadcasting). --- Source: https://pocketpages.dev/docs/speedruns/custom-domain-fly-cloudflare # Speedrun: Connecting Your Fly.io App to a Custom Domain with Cloudflare Proxy Custom domains on your Fly.io app with Cloudflare in front can be a little complex because you must validate the domain on Fly.io BEFORE turning on Cloudflare proxying. Follow these steps. ## 1. Create the Fly.io App - Start by deploying your app on [Fly.io](https://fly.io/). Follow the standard process to get your app up and running. ## 2. Register Your Domain - If you haven't already, register your domain. It's often convenient to register it through [Cloudflare](https://cloudflare.com), which will also handle your DNS and proxying needs. ## 3. Configure DNS in Cloudflare - In Cloudflare's DNS settings, add **A** and **AAAA** records pointing to your Fly.io app's public IPv4 and IPv6 addresses. - **Important:** Turn off proxying (the orange cloud icon) for these records. This ensures that the Fly.io app can be accessed directly. ## 4. Add a Certificate in Fly.io - In your Fly.io dashboard, add an SSL certificate for your custom domain. - Since proxying is turned off, Fly.io should be able to validate the certificate immediately. Your app should now respond on your custom domain, but it's not yet proxied through Cloudflare. ## 5. Verify Domain Ownership and Proxying - From the Fly.io certificate area, add the **CNAME** record required for domain ownership verification. - **Important:** Turn off proxying for the CNAME record as well. Fly.io needs to verify ownership whenever the SSL certificate is renewed, which requires direct access. - Go back to Fly.io, check the certificate, and ensure domain ownership verification is successful. ## 6. Turn On Proxying in Cloudflare - Once everything is verified and working, return to Cloudflare and turn on proxying (enable the orange cloud) for your A and AAAA records. - In Cloudflare’s **SSL/TLS** settings, set the encryption mode to **Full** (not Full Strict) to ensure proper SSL handshakes between Cloudflare and Fly.io. ## 7. Test Your Setup - Finally, browse to your new domain to confirm everything is working as expected with Cloudflare proxying enabled. You now have a fully functioning Fly.io app served through a custom domain with Cloudflare as the proxy! --- Source: https://pocketpages.dev/docs/speedruns/google-oauth2 # Google OAuth2 Setup Guide This guide walks you through setting up Google OAuth2 sign-in for your PocketPages app. ## 1. Create/Select Google Cloud Project 1. Go to [Google Cloud Console](https://console.cloud.google.com) 2. Either select an existing project or create a new one 3. If creating new, provide a project name when prompted ![Creating a new Google Cloud project](2025-02-08-06-54-56.png) ![Naming the new project](2025-02-08-06-56-00.png) ![Selecting the project](2025-02-08-06-56-28.png) ## 2. Configure OAuth Credentials 1. Navigate to "Credentials" in the left sidebar 2. Click "Create Credentials" and select "OAuth client ID" ![Navigating to credentials](2025-02-08-06-56-56.png) ![Creating OAuth credentials](2025-02-08-06-57-07.png) ### Configure Application Type 1. Select "Web application" as the application type 2. Configure your authorized origins and redirect URIs: - **Authorized JavaScript origins**: Your application domain (e.g., `http://localhost:8090`) - **Authorized redirect URIs**: Your auth callback URL (e.g., `http://localhost:8090/auth/oauth/confirm`) ![Selecting web application](2025-02-08-06-57-57.png) ![Configuring URIs](2025-02-08-07-00-42.png) ### Configure Consent Screen (if needed) If you haven't set up a consent screen before, you'll need to configure it: 1. Choose External/Internal user type 2. Fill in the required application information ![Consent screen setup](2025-02-08-06-57-19.png) ![Consent screen details](2025-02-08-06-57-27.png) ### Download Credentials 1. After creating the OAuth client, download the JSON credentials file 2. Store this file securely - it contains sensitive information ![Downloading credentials](2025-02-08-06-58-27.png) ![Credentials JSON format](2025-02-08-06-58-37.png) ## 3. Configure OAuth2 in the dashboard OAuth2 providers belong to an auth collection, usually `users`: 1. Open your app's dashboard (`/_/`) and go to **Collections**. 2. Open the `users` collection's settings (the gear icon) and its **Options** tab. 3. Under **OAuth2**, turn it on. 4. Click **Add provider** and pick **Google**. ![OAuth2 settings for the users collection](2025-02-08-06-59-00.png) ![OAuth2 providers section](2025-02-08-06-59-09.png) ![Adding new provider](2025-02-08-06-59-17.png) ![Selecting Google provider](2025-02-08-06-59-24.png) There's no site URL to set for this. The `auth` plugin builds the redirect URL from the address the request came in on: the scheme and host the browser used, plus `/auth/oauth/confirm`. So the redirect URI in Google must match that address exactly. `http://localhost:8090` and `http://127.0.0.1:8090` are different to Google, so add each one you use, plus your live domain (`https://example.com/auth/oauth/confirm`). Behind a proxy, the host is the one the browser asked for, and HTTPS is detected from `X-Forwarded-Proto`. ### Provider Configuration 1. Enter your Client ID and Client Secret from the downloaded credentials 2. Configure any additional auth options as needed 3. Save your changes ![Configuring Google provider](2025-02-08-06-59-32.png) ![Saving changes](2025-02-08-06-59-59.png) ## Customizing the Return URL By default, the `auth` plugin uses `/auth/oauth/confirm` as the OAuth2 return path. Change it when you start the flow: ```js ctx.session.requestOAuth2('google', { redirectPath: '/custom/oauth/callback' }) ``` Remember to add the new redirect URL to your Google OAuth2 configuration too. ## Implementation Guide ### 1. Turn on the auth plugin ```js // pb_pages/+config.js module.exports = { plugins: ['auth'], } ``` ### 2. Login form ```html
    ``` ### 3. Start the flow ```js // pb_pages/auth/oauth/+page.js module.exports = { post(ctx) { ctx.session.requestOAuth2(ctx.req.body().provider) }, } ``` `requestOAuth2` stores its state in a cookie and redirects the user to Google's consent screen. ### 4. Callback ```js // pb_pages/auth/oauth/confirm/+page.js module.exports = { load(ctx) { try { ctx.session.signInWithOAuth2(ctx.req.query('state'), ctx.req.query('code')) } catch (e) { return { error: e.message } } return ctx.res.redirect('/') }, } ``` ```ejs <%= data.error %> ``` ### 5. Migration Set up Google OAuth2 in a PocketBase migration: ```js migrate( (app) => { const users = app.findCollectionByNameOrId('users') users.oauth2.enabled = true users.oauth2.providers = [ { name: 'google', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, ] app.save(users) }, (app) => { const users = app.findCollectionByNameOrId('users') users.oauth2.enabled = false users.oauth2.providers = [] app.save(users) } ) ``` ### 6. Protected routes ```js // pb_pages/account/+middleware.js module.exports = (ctx, next) => { if (!ctx.auth) return ctx.res.redirect('/login') return next() } ``` ### 7. Auth state in the UI ```ejs <% if (ctx.auth) { %>
    Welcome, <%= ctx.auth.email() %>
    <% } else { %> Log in <% } %> ``` ### 8. Logout ```js // pb_pages/logout/+page.js module.exports = { post(ctx) { ctx.session.signOut() return ctx.res.redirect('/') }, } ``` See [Authentication](https://pocketpages.dev/docs/authentication) and the [auth plugin](https://pocketpages.dev/docs/plugins/auth). ## Troubleshooting Common issues and solutions: - **Invalid redirect URI**: Ensure your redirect URI exactly matches what's configured in Google Cloud Console - **Consent screen not showing**: Make sure you've properly configured the OAuth consent screen - **Authentication failed**: Verify your client ID and secret are correctly copied to the dashboard ## Security Considerations - Always use HTTPS in production - Keep your client secret secure - Regularly rotate credentials - Review Google OAuth2 access regularly in your Google Cloud Console --- Source: https://pocketpages.dev/docs/speedruns/ses # Speedrun: Setting Up Email with Google Suite and AWS SES - [Prerequisite: Make sure you can receive emails first](#prerequisite-make-sure-you-can-receive-emails-first) - [Create an SES Identity](#create-an-ses-identity) - [Add DNS Records](#add-dns-records) - [Add a custom FROM domain](#add-a-custom-from-domain) - [Add DMARC settings](#add-dmarc-settings) - [Verifying the Setup](#verifying-the-setup) - [Submit for Approval](#submit-for-approval) - [Creating SMTP Credentials](#creating-smtp-credentials) - [Configure SMTP in the dashboard](#configure-smtp-in-the-dashboard) ## Prerequisite: Make sure you can receive emails first To receive emails, you'll need an email provider. I use Google Suite, but you can choose any provider you prefer. [Setting up a new email domain in Google Suite](https://pocketpages.dev/docs/speedruns/gs-gmail). (Someone should write about how to do it using Proton.me) ## Create an SES Identity Log in to your Amazon SES account and follow their getting started guide to create a FROM address and sending domain. Make sure you're in the region you prefer. This is important if you have existing domains because AWS frowns upon approving multiple sending regions. ![](2024-09-08-20-29-10.png) Start by creating an Identity: ![](2024-09-08-20-30-52.png) ![](2024-09-08-20-33-41.png) ## Add DNS Records You'll need to add DNS records provided by SES to your DNS provider. Unlike Google Suite, you'll need to enter these values manually. They do not provide integrations with any DNS providers. ![AWS SES DNS Setup](2024-09-03-06-20-55.png) **Note for Cloudflare users: If you’re using Cloudflare, make sure these records are not proxied.** ![](2024-09-08-22-28-33.png) ## Add a custom FROM domain Deliverability is better if you add a custom FROM domain: ![](2024-09-08-22-38-12.png) ![](2024-09-08-22-38-51.png) It requires a few additional DNS entries. Note that the MX `priority` goes into a separate field, not the MX server field: ![](2024-09-08-22-41-08.png) ![](2024-09-08-22-42-35.png) ## Add DMARC settings ![](2024-09-08-22-45-05.png) ## Verifying the Setup After adding the DNS records, go back to AWS SES and wait for the domain to show as verified. Then, send a verification email. You should receive it if everything is set up correctly. ![](2024-09-08-22-32-26.png) ![](2024-09-08-22-35-46.png) If verification takes too long, go to **Identities > DKIM**, click **Edit**, then **Save** to trigger an immediate re-verification. ![](2024-09-08-22-33-32.png) ## Submit for Approval Before you can send emails to anyone, you must submit everything for approval in AWS SES. This step is crucial to avoid issues when sending emails outside your verified domain. If you have previously had a domain approved, you may be able to skip this step. To find out, simply try sending a test message to anything with a different domain. ## Creating SMTP Credentials Create SMTP credentials in the AWS SES console. These credentials will be used in your app's dashboard for sending emails. ![](2024-09-08-22-48-53.png) ## Configure SMTP in the dashboard Once you have your SMTP credentials, head over to the dashboard (Settings → Mail). Enter the SMTP credentials in the dashboard, and ensure the **SENDER** address is correctly set. If SES hasn't verified your email yet, you can test it by sending an email to `test@`, which should go through if the domain is the same. ![](2024-09-08-22-53-02.png) --- Source: https://pocketpages.dev/docs/speedruns/gs-gmail # Setting up a new email domain in Google Suite The process of setting up a new email domain in Google Suite involves several steps. In this guide, we will walk you through the process, from adding the domain to activating Gmail and setting up a catch-all email. By following these steps, you'll be able to configure your email domain effectively and ensure smooth communication within your organization. Let's get started! - [Add the domain](#add-the-domain) - [Domain Verification](#domain-verification) - [Activating Gmail](#activating-gmail) - [Adding a Catch-All Email](#adding-a-catch-all-email) - [Test Your Email Setup](#test-your-email-setup) - [Add a Sender Account to Gmail](#add-a-sender-account-to-gmail) ## Add the domain Go to the [domains admin](https://admin.google.com/ac/domains/manage) and add a new domain. ![](2024-09-08-19-12-14.png) Set up an "alias domain," which involves a verification step where you need to update your DNS records. Otherwise, you may have to do the following steps manually. ![](2024-09-08-19-04-47.png) ## Domain Verification If you're using Cloudflare as your DNS manager, Google will automatically recognize it and add the necessary DNS records. ![](2024-09-08-19-06-15.png) ![](2024-09-08-19-07-10.png) Then, wait for domain verification to complete. It should be fast. ![](2024-09-08-19-07-35.png) ## Activating Gmail ![](2024-09-08-19-11-38.png) ![](2024-09-08-19-12-59.png) Once again, Cloudflare makes it easy and automatic. Otherwise, this may involve manual steps if Google is not integrated with your DNS provider. ![](2024-09-08-19-14-04.png) ![](2024-09-08-19-15-06.png) ## Adding a Catch-All Email I set up a catch-all email so that any email sent to `@pocodex.dev` is routed to `ben@pocodex.dev` if the specific email address doesn’t exist. This is optional, but you might want to consider what happens to unrecognized email addresses in your setup. [This Google help article](https://apps.google.com/supportwidget/articlehome) covers it, but here it is below too: I like to go to [Default Routing](https://admin.google.com/ac/apps/gmail/defaultrouting) and add a rule: ![](2024-09-08-19-21-45.png) Use a regex to match the entire domain like `@pocodex\.dev$`. I also like to prepend `[CATCHALL] - ` to the subject so I know that it wasn't sent to my "real" address. ![](2024-09-08-19-25-59.png) Redirect the emails to your "real" email address: ![](2024-09-08-19-25-14.png) Finally, make sure you only perform this on unrecognized email addresses. ![](2024-09-08-19-24-55.png) ![](2024-09-08-19-51-48.png) ## Test Your Email Setup Send an email to yourself using the new domain to ensure that everything is working correctly. You may need to wait a bit for the MX records to propagate. Just because Google says everything is verified doesn't mean the Internet at large has received the memo. ![](2024-09-08-19-39-27.png) If you want to be extra sure, try sending from a completely different email provider like Proton or AOL. Once you receive messages, you're all set! ## Add a Sender Account to Gmail Sometimes you might want to send email FROM your domain, such as replies or customer messages. To do that, go to your user settings in Gmail and add an account: ![](2024-09-08-19-56-56.png) ![](2024-09-08-19-57-35.png)