Skip to content

Instantly share code, notes, and snippets.

@danielres
Last active November 22, 2023 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielres/e6fe298369afcc8edfe686b8ef090a48 to your computer and use it in GitHub Desktop.
Save danielres/e6fe298369afcc8edfe686b8ef090a48 to your computer and use it in GitHub Desktop.
Sveltekit + Pocketbase SSR

Sveltekit + Pocketbase SSR

The minimal steps to integrate Pocketbase with Sveltekit SSR. Not striclty needed as Pocketbase can be used from the browser only. But useful in certain cases.

// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
import PocketBase, { Admin } from 'pocketbase'
declare global {
declare namespace App {
// interface Error {}
interface Locals {
pb: PocketBase
user: Record | Admin | null
}
// interface PageData {}
// interface Platform {}
}
}
import PocketBase from 'pocketbase';
const pb = new PocketBase("http://127.0.0.1:8090");
pb.authStore.loadFromCookie(document.cookie);
const unsubscribe = pb.authStore.onChange(() => {
currentUser.set(pb.authStore.model)
document.cookie = client.authStore.exportToCookie({ httpOnly: false });
}, true)
export default client;
import { createInstance } from './routes/pocketbase/utils/pocketbase'
import type { Handle } from '@sveltejs/kit'
export const handle: Handle = async ({ event, resolve }) => {
const pb = createInstance()
// load the store data from the request cookie string
pb.authStore.loadFromCookie(event.request.headers.get('cookie') || '')
try {
// get an up-to-date auth store state by verifying and refreshing the loaded auth model (if any)
if (pb.authStore.isValid) await pb.collection('users').authRefresh()
} catch (_) {
pb.authStore.clear() // clear the auth store on failed refresh
}
event.locals.pb = pb
event.locals.user = pb.authStore.model
const response = await resolve(event)
// send back the default 'pb_auth' cookie to the client with the latest store state
response.headers.set('set-cookie', pb.authStore.exportToCookie({ httpOnly: false }))
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment