Integration guide
Start with the SvelteKit adapter.
The cards use real Svelte components. Configure the adapter once, then add LoginLink, RegisterLink, ConnectionLink, or LogoutLink to your pages. The files below come directly from this repository’s SvelteKit integration example.
- Use examples/sveltekit-integration in the Plazia Identity repository. It includes the two workspace SDK packages, SvelteKit, and PostgreSQL dependencies. Run pnpm install from the repository root.
- Register a regular_web application with client_secret_basic and the oauth2_1 profile. Register http://localhost:5174/api/auth/callback and http://localhost:5174 as its exact callback and logout URLs for local development; use HTTPS in production.
- Copy env.example to .env in the example directory. Replace the issuer, client ID, client secret, database URL, and session key with your configuration. Generate the 32-byte session key with openssl rand -base64 32 and keep it and the client secret on the server.
- Create the session tables with psql against the configured database using session-schema.psql. All application instances need the same database and encryption key. Schedule deletion of expired app_auth_sessions rows.
- Run pnpm --filter plazia-identity-integration-example dev from the repository root. Open http://localhost:5174; /custom includes the email entry example. The callback returns to /dashboard.
- For SSO, supply Company.svelte with a connectionId enabled for this application. For passkeys, enable the hosted passkey flow with the correct RP ID and allowed origin on the issuer.
.env
PLZI_ISSUER_URL=https://tenant.identity.example.test
PLZI_OAUTH_PROFILE=oauth2_1
PLZI_CLIENT_ID=registered-confidential-client-id
PLZI_CLIENT_SECRET=server-held-client-secret
PLZI_SESSION_DATABASE_URL=postgresql://app:password@localhost:5432/app
PLZI_SESSION_KEY_BASE64=base64-encoded-32-byte-key
PLZI_APP_ORIGIN=http://localhost:5174
PLZI_REDIRECT_URL=http://localhost:5174/api/auth/callback
PLZI_POST_LOGIN_REDIRECT_URL=http://localhost:5174/dashboard
PLZI_POST_LOGOUT_REDIRECT_URL=http://localhost:5174session-schema.psql
CREATE TABLE app_auth_sessions (
id UUID PRIMARY KEY,
handle_digest TEXT NOT NULL UNIQUE,
origin TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE app_auth_session_values (
session_id UUID NOT NULL REFERENCES app_auth_sessions(id) ON DELETE CASCADE,
key TEXT NOT NULL,
nonce BYTEA NOT NULL,
ciphertext BYTEA NOT NULL,
PRIMARY KEY (session_id, key)
);
CREATE INDEX app_auth_sessions_expiry ON app_auth_sessions (expires_at);src/lib/server/auth-session.ts
import type { SessionStorage } from "@plazia/identity-frontend-sdk";
import type { BffSession } from "@plazia/identity-sveltekit";
import { env } from "$env/dynamic/private";
import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
import { Pool } from "pg";
import type { Cookies } from "@sveltejs/kit";
const sessionTtlSeconds = 24 * 60 * 60;
const pool = new Pool({
connectionString: env.PLZI_SESSION_DATABASE_URL,
max: 8,
allowExitOnIdle: true,
connectionTimeoutMillis: 3000,
statement_timeout: 5000,
application_name: "plazia-sveltekit-example-bff",
});
function key(): Buffer {
const value = Buffer.from(env.PLZI_SESSION_KEY_BASE64 ?? "", "base64");
if (value.length !== 32) throw new Error("Identity BFF requires a 32-byte session key.");
return value;
}
function digest(handle: string): string {
return createHash("sha256").update(handle).digest("hex");
}
function seal(value: string, sessionId: string, name: string): [Buffer, Buffer] {
const nonce = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", key(), nonce);
cipher.setAAD(Buffer.from(`${sessionId}:${name}`));
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final(), cipher.getAuthTag()]);
return [nonce, ciphertext];
}
function open(nonce: Buffer, ciphertext: Buffer, sessionId: string, name: string): string {
const decipher = createDecipheriv("aes-256-gcm", key(), nonce);
decipher.setAAD(Buffer.from(`${sessionId}:${name}`));
decipher.setAuthTag(ciphertext.subarray(-16));
return Buffer.concat([decipher.update(ciphertext.subarray(0, -16)), decipher.final()]).toString("utf8");
}
function setCookie(cookies: Cookies, name: string, handle: string, secure: boolean): void {
cookies.set(name, handle, {
httpOnly: true,
sameSite: "lax",
secure,
path: "/",
maxAge: sessionTtlSeconds,
});
}
export async function sessionFor(cookies: Cookies, origin: string): Promise<BffSession> {
key();
if (!env.PLZI_SESSION_DATABASE_URL) throw new Error("Identity BFF session database is unavailable.");
const secure = new URL(origin).protocol === "https:";
const name = secure ? "__Host-plazia_session" : "plazia_session";
const candidate = cookies.get(name);
const validCandidate = candidate && /^[A-Za-z0-9_-]{43}$/.test(candidate) ? candidate : undefined;
let handle = validCandidate ?? "";
let sessionId: string | undefined;
if (validCandidate) {
const result = await pool.query<{ id: string }>(
"SELECT id FROM app_auth_sessions WHERE handle_digest = $1 AND origin = $2 " +
"AND expires_at > CURRENT_TIMESTAMP",
[digest(validCandidate), origin],
);
sessionId = result.rows[0]?.id;
}
if (!sessionId) {
handle = randomBytes(32).toString("base64url");
sessionId = randomUUID();
await pool.query(
"INSERT INTO app_auth_sessions (id, handle_digest, origin, expires_at) " +
"VALUES ($1, $2, $3, CURRENT_TIMESTAMP + $4::integer * INTERVAL '1 second')",
[sessionId, digest(handle), origin, sessionTtlSeconds],
);
setCookie(cookies, name, handle, secure);
}
const id = sessionId;
const storage: SessionStorage = {
async getItem(item) {
const result = await pool.query<{ nonce: Buffer; ciphertext: Buffer }>(
"SELECT value.nonce, value.ciphertext FROM app_auth_session_values AS value " +
"JOIN app_auth_sessions AS session ON session.id = value.session_id " +
"WHERE session.id = $1 AND session.handle_digest = $2 AND session.origin = $3 " +
"AND session.expires_at > CURRENT_TIMESTAMP AND value.key = $4",
[id, digest(handle), origin, item],
);
const row = result.rows[0];
return row ? open(row.nonce, row.ciphertext, id, item) : null;
},
async setItem(item, value) {
const [nonce, ciphertext] = seal(value, id, item);
const result = await pool.query(
"INSERT INTO app_auth_session_values (session_id, key, nonce, ciphertext) " +
"SELECT id, $4, $5, $6 FROM app_auth_sessions " +
"WHERE id = $1 AND handle_digest = $2 AND origin = $3 " +
"AND expires_at > CURRENT_TIMESTAMP FOR UPDATE " +
"ON CONFLICT (session_id, key) DO UPDATE SET nonce = EXCLUDED.nonce, ciphertext = EXCLUDED.ciphertext",
[id, digest(handle), origin, item, nonce, ciphertext],
);
if (result.rowCount !== 1) throw new Error("Identity BFF session was replaced.");
},
async removeItem(item) {
await pool.query(
"DELETE FROM app_auth_session_values WHERE session_id = $1 AND key = $4 " +
"AND EXISTS (SELECT 1 FROM app_auth_sessions WHERE id = $1 AND handle_digest = $2 AND origin = $3 " +
"AND expires_at > CURRENT_TIMESTAMP FOR UPDATE)",
[id, digest(handle), origin, item],
);
},
async keys() {
const result = await pool.query<{ key: string }>(
"SELECT value.key FROM app_auth_session_values AS value " +
"JOIN app_auth_sessions AS session ON session.id = value.session_id " +
"WHERE session.id = $1 AND session.handle_digest = $2 AND session.origin = $3 " +
"AND session.expires_at > CURRENT_TIMESTAMP",
[id, digest(handle), origin],
);
return result.rows.map((row) => row.key);
},
};
return {
storage,
async rotate() {
const next = randomBytes(32).toString("base64url");
const result = await pool.query(
"UPDATE app_auth_sessions SET handle_digest = $1 " +
"WHERE id = $2 AND handle_digest = $3 AND origin = $4 AND expires_at > CURRENT_TIMESTAMP",
[digest(next), id, digest(handle), origin],
);
if (result.rowCount !== 1) throw new Error("Identity BFF session was replaced.");
handle = next;
setCookie(cookies, name, handle, secure);
},
async destroy() {
await pool.query("DELETE FROM app_auth_sessions WHERE id = $1 AND handle_digest = $2 AND origin = $3", [id, digest(handle), origin]);
cookies.delete(name, { path: "/" });
},
};
}src/hooks.server.ts
import { sessionHooks } from "@plazia/identity-sveltekit";
import { env } from "$env/dynamic/private";
import { sessionFor } from "$lib/server/auth-session";
import type { Handle } from "@sveltejs/kit";
export const handle: Handle = async ({ event, resolve }) => {
sessionHooks({
event,
session: await sessionFor(event.cookies, event.url.origin),
clientSecret: env.PLZI_CLIENT_SECRET ?? "",
});
return resolve(event);
};src/routes/api/auth/[action]/+server.ts
export { handleAuth as GET, handleAuth as POST } from "@plazia/identity-sveltekit";src/app.d.ts
import type { AuthLocals } from "@plazia/identity-sveltekit";
declare global {
namespace App {
interface Locals extends AuthLocals {}
}
}
export {};src/routes/(protected)/+layout.server.ts
import { redirect } from "@sveltejs/kit";
import type { LayoutServerLoad } from "./$types";
export const load: LayoutServerLoad = async ({ locals }) => {
const user = await locals.plaziaAuth.getUser();
if (!user) redirect(303, "/");
return { user };
};