UNPKG

better-auth

Version:

The most comprehensive authentication framework for TypeScript.

58 lines (57 loc) 2.11 kB
import { parseSetCookieHeader, toCookieOptions } from "../cookies/cookie-utils.mjs"; import { PACKAGE_VERSION } from "../version.mjs"; import { warnIfCookiePluginNotLast } from "./cookie-plugin-guard.mjs"; import { createAuthMiddleware } from "@better-auth/core/api"; //#region src/integrations/svelte-kit.ts const toSvelteKitHandler = (auth) => { return (event) => auth.handler(event.request); }; const svelteKitHandler = async ({ auth, event, resolve, building }) => { if (building) return resolve(event); const { request, url } = event; if (isAuthPath(url.toString(), auth.options)) return auth.handler(request); return resolve(event); }; function isAuthPath(url, options) { const _url = new URL(url); const baseURLStr = typeof options.baseURL === "string" ? options.baseURL : void 0; const baseURL = new URL(`${baseURLStr || _url.origin}${options.basePath || "/api/auth"}`); if (_url.origin !== baseURL.origin) return false; if (!_url.pathname.startsWith(baseURL.pathname.endsWith("/") ? baseURL.pathname : `${baseURL.pathname}/`)) return false; return true; } const sveltekitCookies = (getRequestEvent) => { let hasWarned = false; return { id: "sveltekit-cookies", version: PACKAGE_VERSION, hooks: { after: [{ matcher() { return true; }, handler: createAuthMiddleware(async (ctx) => { if (!hasWarned) { warnIfCookiePluginNotLast(ctx.context, "sveltekit-cookies"); hasWarned = true; } const returned = ctx.context.responseHeaders; if ("_flag" in ctx && ctx._flag === "router") return; if (returned instanceof Headers) { const setCookies = returned?.get("set-cookie"); if (!setCookies) return; const event = getRequestEvent(); if (!event) return; const parsed = parseSetCookieHeader(setCookies); for (const [name, attributes] of parsed) try { event.cookies.set(name, attributes.value, { ...toCookieOptions(attributes), path: attributes.path || "/" }); } catch {} } }) }] } }; }; //#endregion export { isAuthPath, svelteKitHandler, sveltekitCookies, toSvelteKitHandler };