@affinity-lab/sk-session
v1.1.1
Published
Session manager for SvelteKit projects
Downloads
11
Keywords
Readme
@affinity-lab/sk-session
Session manager for SvelteKit projects
Installation
npm i -s @affinity-lab/sk-session
Usage
Set up the service
$lib/services/session-manager.ts
import SessionManager, { MemoryStorageAdapter } from "@affinity-lab/sk-session";
export let sessionManager = new SessionManager(new MemoryStorageAdapter(3600, 60));
Only MemoryStorageAdapter provided this point, but you can create your on own session storage adapter. It needs to implement the IStorageAdapter
interface.
Declare Session type
src/app.d.ts
declare namespace App {
// interface Error {}
export type SessionData = undefined | {
[p: string]: any,
user?: MyUserType
}
interface Locals {session: SessionData;}
interface PageData {session: SessionData;}
// interface Platform {}
}
Apply it in hooks.server.js
src/hooks.server.ts
import type {Handle, RequestEvent} from "@sveltejs/kit";
import {sessionManager} from "./lib/services/session-manager";
export async function handle({event, resolve}: { event: RequestEvent, resolve: any }) {
sessionManager.handleRequest(event); // <- this will setup the session
let response = await resolve(event);
sessionManager.update(event); // <- this will write the session data
return response;
}
From that point, you can reach session from the RequestEvent
.
let user:MyUserType|undefined = event.session.user;