Pages JavaScript API

Everything the Pages extension adds to pb_hooks and page code, generated from the TypeScript declarations it ships (your app's types.d.ts has the same, so your editor knows them). For how to use it, see its docs; for Go, the Go API.

Types

pages.Data

What ctx.data holds: shared by middleware, handlers and templates. Add your own keys by redeclaring it.

pages.Params

Route parameters ([id] in a path), strings. Never includes query parameters.

pages.CookieOptions

Options for ctx.res.cookie and ctx.res.clearCookie.

Member Type
path? string
domain? string
maxAge? number Seconds.
expires? Date | number | string A Date, milliseconds since the epoch, or a date string.
httpOnly? boolean Default true.
secure? boolean Default: true on HTTPS.
sameSite? "Lax" | "Strict" | "None" | "lax" | "strict" | "none" Default "Lax".

pages.Request

ctx.req: the request.

Member Type
readonly method string "GET", "POST", ...
readonly url { href: string; origin: string; pathname: string; search: string }
query() (): { [name: string]: string } Every query parameter's first value.
query() (name: string, opts: { all: true }): string[] Every value of a query parameter.
query() (name: string, opts?: { all?: false }): string | undefined A query parameter's first value, or undefined.
header() (name: string): string A request header, '' if absent.
cookie() (name: string, opts: { json: true }): T | undefined A cookie parsed as JSON (undefined if absent or not JSON).
cookie() (name: string, opts?: { json?: false }): string | undefined A cookie's value, or undefined.
cookies() (): { [name: string]: string }
body() (): T The parsed body: a JSON value, or form fields as { name: value } (repeated names as arrays).
files() (name: string): filesystem.File[] Uploaded files of a multipart field, ready for a record's file field.
readonly ip string The client's IP, as PocketBase resolves it.
readonly event core.RequestEvent The underlying PocketBase request event, for anything not covered here.

pages.EventStream

What ctx.res.sse() returns.

Member Type
send() (event: string, data: any, opts?: { id?: string | number; retry?: number }): void Sends an event; non-string data is JSON-encoded.
comment() (text: string): void Writes an SSE comment (: text), which browsers ignore.
close() (): void

pages.Response

ctx.res: the response. Every method that sends ends the request (later steps are skipped).

Member Type
status() (code: number): Response The status for the rendered page.
header() (name: string): string Reads a response header back.
header() (name: string, value: string | number): Response Sets a response header.
cookie() (name: string, value: any, opts?: CookieOptions): Response Sets a cookie; a non-string value is JSON-encoded.
clearCookie() (name: string, opts?: Pick<CookieOptions, "path" | "domain">): Response Expires a cookie (same path/domain as when it was set).
redirect() (location: string, opts?: number | { status?: number; flash?: any }): Response Sends a redirect (3xx, default 302). flash sets a one-time message the next request reads with ctx.flash().
json() (data: any): Response
json() (status: number, data: any): Response
html() (html: string): Response HTML as-is, without layouts.
html() (status: number, html: string): Response
text() (text: string): Response
text() (status: number, text: string): Response
file() (path: string): Response Sends a file from pb_pages (path relative to pb_pages).
sse() (opts?: { keepAlive?: number }): EventStream Starts a text/event-stream response. keepAlive (seconds) writes a comment that often while the handler runs, so proxies keep a quiet stream open.
layout() (on: boolean): Response layout(false) renders this page without layouts (e.g. an htmx fragment).
readonly sent boolean True once a response has been sent.

pages.Route

Member Type
path string The URL pattern without groups: /products/[id].
name string The file name without its extension: [id], index.
file string The file relative to pb_pages, groups included.

pages.Log

Member Type
debug() (...args: any[]): void Shows only in dev mode (or with debug: true).
info() (...args: any[]): void
warn() (...args: any[]): void
error() (...args: any[]): void

pages.ResolveMode

ctx.resolve modes.

type pages.ResolveMode = "require" | "raw" | "script" | "style";

pages.SignedIn

What every sign-in method returns.

Member Type
token string
record core.Record

pages.Session

ctx.session: cookie sessions on PocketBase auth. Present when the auth plugin is on.

Member Type
authMethods() (opts?: { collection?: string }): { password: { enabled: boolean; identityFields: string[] }; otp: { enabled: boolean }; mfa: { enabled: boolean }; oauth2: { enabled: boolean; providers: { name: string; displayName: string }[] }; }
register() (email: string, password: string, opts?: { collection?: string; data?: { [field: string]: any }; verify?: boolean; signIn?: boolean }): SignedIn Creates the record; sends the verification email when verify; signs in when signIn (else token is '').
signInWithPassword() (identity: string, password: string, opts?: { collection?: string }): SignedIn
requestOTP() (email: string, opts?: { collection?: string; create?: boolean }): string Always returns an id (unknown emails get one that never validates).
signInWithOTP() (otpId: string, code: string, opts?: { collection?: string }): SignedIn
signInAnonymously() (opts?: { collection?: string }): SignedIn
requestOAuth2() (provider: string, opts?: { collection?: string; redirectPath?: string; redirect?: boolean }): string Returns the provider's URL; with redirect (default) it also sends the redirect.
signInWithOAuth2() (state: string, code: string, opts?: { createData?: { [field: string]: any } }): SignedIn & { meta: { isNew: boolean; [key: string]: any } }
signIn() (record: core.Record): SignedIn Sets the session cookie for a record the app authenticated itself.
signOut() (): void
requestVerification() (email: string, opts?: { collection?: string }): void
confirmVerification() (token: string): void
requestPasswordReset() (email: string, opts?: { collection?: string }): void
confirmPasswordReset() (token: string, password: string, passwordConfirm: string): void
requestEmailChange() (newEmail: string): void Needs ctx.auth.
confirmEmailChange() (token: string, password: string): void

pages.Realtime

ctx.realtime: PocketBase realtime from page code. Present when the realtime plugin is on.

Member Type
send() (topic: string, data: any, opts?: { filter?: (client: subscriptions.Client) => boolean }): void Sends to every client subscribed to topic (filter only narrows that set). data is always JSON-encoded.
client() (id: string): subscriptions.Client | null One client by id, or null.
subscribe() (topic: string, opts?: { filter?: string; expand?: string; fields?: string }): RealtimeSubscription<T> Listens to topic like a browser on /api/realtime, as this visitor: the collection's list/view rules apply, and filter, expand and fields work as in the JS SDK's subscribe options. Read it with for await. Record topics (posts/*, posts/RECORD_ID) give { action, record }; other topics give the data sent to them. It ends when the request does, on close(), or (throwing) if the page falls 64 messages behind.

pages.RealtimeRecordMessage

A record change from ctx.realtime.subscribe().

Member Type
action "create" | "update" | "delete"
record { [field: string]: any }

pages.RealtimeSubscription

What ctx.realtime.subscribe() returns.

Member Type
close() (): void Ends the subscription; a waiting for await finishes.

pages.Context

The request context, passed to middleware, handlers, templates, components and plugins.

Member Type
req Request
res Response
data Data
params Params
route Route
auth core.Record | null The authenticated record, or null.
app PocketBase The app ($app).
dev boolean True in dev mode.
readonly pagesDir string The absolute path of this app's pb_pages folder.
env() (name: string): string An environment variable, '' if unset.
log Log
meta() (key: string): any Reads a page metadata value (title, description).
meta() (key: string, value: T): T Sets a page metadata value; returns it.
asset() (path: string): string URL of a static file in pb_pages with its content hash: /assets/app.3f9a1c2b7d4e.css.
include() (name: string, locals?: { [key: string]: any }): any Renders a _private/ partial and returns its text (a promise when the partial is async).
resolve() (name: string, opts?: { mode?: "require" }): T Loads a module's exports from _private/.
resolve() (name: string, opts: { mode: "raw" | "script" | "style" }): string Reads a _private/ file as text, or wrapped in <script>/<style>.
store() (name: string): T Reads the app's in-memory store.
store() (name: string, value: T): T Sets a value in the app's in-memory store; returns it.
flash() (): T | undefined The one-time message set by ctx.res.redirect(..., { flash }), or undefined.
pb() (): any A PocketBase JS SDK client acting as the signed-in user (or a guest), in-process.
httpError() (status: number, message?: string): Error An error to throw: sends status with message (JSON from an endpoint, unless the request asks for HTML).
error? { status: number; message: string } Set while +error renders.
session Session Needs the auth plugin in +config.
realtime Realtime Needs the realtime plugin in +config.

pages.HandlerResult

What a handler may return: a plain object is shallow-assigned into ctx.data.

type pages.HandlerResult = Partial<Data> | Response | void | undefined;

pages.Handler

type pages.Handler = (ctx: Context) => HandlerResult | Promise<HandlerResult>;

pages.Handlers

The exports of a route's .ts file: a page's code, or an endpoint (all optional).

Member Type
load? Handler Runs for every method, before the method's handler.
get? Handler
post? Handler
put? Handler
patch? Handler
delete? Handler

pages.Middleware

A +middleware.js export. Call next() to continue and return its result.

type pages.Middleware = (ctx: Context, next: () => any) => any;

pages.Plugin

What a JS plugin factory returns. Every hook is optional.

Member Type
name string Required and unique.
extendContext() (ctx: Context): void Adds to ctx, before any onRequest.
onRequest() (ctx: Context): void | Promise<void> Before middleware.
transform() (e: { html: string; ctx: Context; file: string }): string After each page or layout renders (not partials); returns the new HTML.

pages.PluginFactory

A JS plugin: a factory that gets its entry's options from +config.

type pages.PluginFactory = (config: { [key: string]: any }) => Plugin;

pages.Config

The export of +config.js.

Member Type
plugins? (string | PluginFactory | ({ factory: PluginFactory } & { [option: string]: any }))[] Module names, built-in names (auth, realtime), factories, or { factory, ...options }.
debug? boolean Detailed error pages and ctx.log.debug output outside dev mode.

pages.Props

The props pages passes to a JSX/TSX page, layout or partial it renders (an include's locals typed by L). A component you import and use as <Card /> gets only the props you give it, so type those yourself.

Member Type
ctx Context
data Data
params Params
meta Context["meta"]
asset Context["asset"]
include Context["include"]
slot { (name?: string): any; (name: string, content: any): void } slot(name) reads a slot, slot(name, content) sets one, slot() is children.
children? any In a layout, the inner content.

JSX.Element

type JSX.Element = any;

JSX.ElementChildrenAttribute

Member Type
children {}

JSX.IntrinsicElements