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.
Last active
November 22, 2023 13:03
-
-
Save danielres/e6fe298369afcc8edfe686b8ef090a48 to your computer and use it in GitHub Desktop.
Sveltekit + Pocketbase SSR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 {} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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