@velastack/pocketbase

PocketBase bindings for SvelteKit: a hooks.server.ts middleware, a typed client and type-safe collection schemas. This is the package the generated code imports.

npm install @velastack/pocketbase

Installed for you by vela create and vela enable backend.

Entrypoints

  • @velastack/pocketbase - The middleware and the client
  • @velastack/pocketbase/form - Superforms helpers
  • @velastack/pocketbase/auth - requireUser, the signed-in user for the current request
  • @velastack/pocketbase/api-key - API key generation and verification
  • @velastack/pocketbase/testing - The TestContext type for server tests

handlePocketbase

Configures the PocketBase middleware in hooks.server.ts.

import { handlePocketbase } from '@velastack/pocketbase';
import {
    POCKETBASE_URL,
    POCKETBASE_SUPERUSER_EMAIL,
    POCKETBASE_SUPERUSER_PASSWORD
} from '$app/env/private';

export const handle = handlePocketbase({
	pocketbaseUrl: POCKETBASE_URL,
	superuserEmail: POCKETBASE_SUPERUSER_EMAIL,
	superuserPassword: POCKETBASE_SUPERUSER_PASSWORD
})

The auth, api and apiKeys blocks are added to this call by the enable commands. It puts two clients on locals: admin, which queries the database directly, and pb, which is scoped to the authenticated user.

From 0.5.1 both have the PocketBase SDK’s auto-cancellation turned off. The SDK aborts a pending request when another to the same endpoint starts, which suits a browser re-running a search as someone types; on the server it made a Promise.all of several create calls to one collection fail with “The request was aborted”. Overlapping requests on locals.pb and locals.admin now all run to completion.

setDefaultData

Sets the default data for a form from a PocketBase record. Exported from the /form entrypoint.

import { setDefaultData } from '@velastack/pocketbase/form';

export const actions = {
	default: async ({ locals, request }) => {
        const record = await locals.admin.collection('posts').getOne(1);
        setDefaultData(form, record);
        return { form };
    }
}

setPocketbaseErrors

Sets PocketBase errors as Superforms errors when a form submission fails.

import { setPocketbaseErrors } from '@velastack/pocketbase/form';

export const actions = {
	default: async ({ locals, request }) => {
        try {
            await locals.admin.collection('posts').create(form.data);
        } catch (error) {
            setPocketbaseErrors(form, error);
            return fail(400, { form });
        }
    }
}

requireUser

Returns the signed-in user of the current request, or throws error(401). From 0.5.3, in the /auth entrypoint. Call it first in every remote function that needs a session:

import { command, getRequestEvent } from '$app/server';
import { requireUser } from '@velastack/pocketbase/auth';

export const changePassword = command(schema, async ({ password }) => {
	const user = requireUser();
	const { locals } = getRequestEvent();
	await locals.admin
		.collection('users')
		.update(user.id, { password, passwordConfirm: password });
});

The auth.protectedRoutes of handlePocketbase protect pages, form actions and +server.ts endpoints: it goes by the route the code lives in. A remote function is different. It is an endpoint of its own, and the request does not say where its file is. A query carries no route at all, and for a form or a command the route is the page the browser says it called from, in a header the browser writes. So a function in src/routes/(app) can be called without a session, by leaving that header off or pointing it at /login. SvelteKit’s documentation says the same: run the check inside the function, and never use route, params or url to decide what a caller may do.

What requireUser returns is the user the middleware verified for this request: the record PocketBase gave back for the session token, never what the cookie claims. A forged or expired cookie is a 401. It throws and does not redirect, because a command cannot redirect.

A function that has to work without a session (sign-in, sign-up, password reset) does not call it. The functions vela enable auth --remote and the --remote generators write under (app) all do.

Page loads, form actions and +server.ts endpoints under a protected route are already protected, since their route is where they live. requireUser is still the way to get the user there, and what the generated code uses everywhere a session is needed:

export const load = async ({ locals }) => {
	const user = requireUser();
	const notes = await locals.pb
		.collection('notes')
		.getFullList({ filter: locals.pb.filter('owner = {:owner}', { owner: user.id }) });
	return { notes };
};

The alternative, locals.pb.authStore.record!, only tells the compiler there is a user: it checks nothing, and the record it gives has no field types. requireUser checks, and returns your own users record, so user.name and user.email are typed.

API keys

The primitives behind vela enable api-keys. Keys are stored hashed, so the secret is only ever shown once, at generation.

import {
    generateApiKeySecret,
    hashApiKey,
    verifyApiKey
} from '@velastack/pocketbase/api-key';

Generated types

vela sync augments this package with Models, Collections and Schemas for your project’s collections, so locals.pb.collection('posts') is typed. The file is .svelte-kit/pocketbase/$types.d.ts, included from tsconfig.json.

Models is what PocketBase returns and Schemas is what it accepts. A record always arrives with every field filled in, an unset one holding '', 0, false or [], so Models fields are not optional and need no ?? ''; only hidden fields and a non-required auth email are. See vela sync for what changed in 0.31.0 and what to update in existing code.