Auth

The auth utility signs users in with Google, GitHub, or Vercel and keeps them signed in with a session cookie stored in MongoDB. It talks to the provider with fetch and creates tokens with Node's crypto, so there is no auth library underneath. Each provider is one class in src/lib/server/auth that extends AuthSession, so a single object such as googleAuth builds the sign in URL, checks the callback, and manages the session.

Installation

Install the item for your provider. Each one pulls in auth-base with the session code and the sign out route, and the MongoDB utility that stores users and sessions.

  • Install auth-google for Google sign in
  • Install auth-github for GitHub sign in
  • Install auth-vercel for Vercel sign in
pnx remote0 add https://plainsv.com/r/auth-google.json

Then set your site URL, your MongoDB connection string, and the provider's keys in .env.

.env
DOMAIN_URL="http://localhost:5173"
MONGODB_URI=""
GOOGLE_CLIENT_ID=""
GOOGLE_CLIENT_SECRET=""
.env
DOMAIN_URL="http://localhost:5173"
MONGODB_URI=""
GITHUB_CLIENT_ID=""
GITHUB_CLIENT_SECRET=""
.env
DOMAIN_URL="http://localhost:5173"
MONGODB_URI=""
VERCEL_CLIENT_ID=""
VERCEL_CLIENT_SECRET=""

Provider setup

Create an OAuth app with your provider, and register its callback route on your DOMAIN_URL as the callback URL. Add a second app or URL for production, since providers only redirect to registered URLs.

  • Create a Google OAuth client in the Google Cloud console with the redirect URI http://localhost:5173/api/auth/google/callback
  • Create a GitHub OAuth app in your GitHub developer settings with the callback URL http://localhost:5173/api/auth/github/callback
  • Create a Vercel app under your team's Settings, Apps, add the authorization callback URL http://localhost:5173/api/auth/vercel/callback, enable the openid, email, and profile scopes under Permissions, and set its client authentication to client_secret_post
  • Copy the client ID and secret into .env

Hook

Auth loads the signed-in user with the provider's hook, which you run before your main hook in src/hooks.server.ts. On every request it reads the session cookie and loads the session and user into event.locals.sessionData and event.locals.userData. Every provider shares the same hook, so use any installed one.

The init item installs src/hooks.server.ts with one handle that adds the dark class to <body>. Rename it to mainHandle, then export a new handle that runs hook first with sequence.

src/hooks.server.ts
import { sequence } from "@sveltejs/kit/hooks";
import { googleAuth } from "#lib/server/auth/google.js";
import type { Handle } from "@sveltejs/kit/hooks";

/** Adds the `dark` class to `<body>` on the server */
const mainHandle: Handle = async ({ event, resolve }) => {
	// Handle `dark` class on body on the server side to avoid flicker from light to dark
	if (event.request.method === "GET" && event.route.id !== null) {
		event.locals.isDarkMode = event.cookies.get("theme") === "dark";
		const response = await resolve(event, { transformPageChunk: ({ html }) => (event.locals.isDarkMode ? html.replace("<body ", '<body class="dark" ') : html) });
		return response;
	}
	return await resolve(event);
};

// Load the signed-in user before the main hook
export const handle = sequence(googleAuth.hook, mainHandle);

Sign in

Link to /api/auth/google, /api/auth/github, or /api/auth/vercel to start sign in. Add callbackURL to send the user back to a page after the callback, which defaults to /.

+page.svelte
<a href="/api/auth/google?callbackURL=/account">Sign in with Google</a>

The sign in route saves a random state, and a PKCE verifier for Google and Vercel, in 10-minute cookies and redirects to the provider. The callback route checks them, exchanges the code for tokens with validateAuthorizationCode, and loads the user's verified email and avatar with getUser. It then finds or creates the user in MongoDB by email and starts a session. getUser throws when the email is not verified, so those users are turned away.

Read the user

Read locals.userData in any server load function or endpoint. It holds the MongoDB user with its _id, email, and image, or null when no one is signed in.

src/routes/account/+page.server.ts
import { redirect } from "@sveltejs/kit";

export const load = async ({ locals }) => {
	// If no one is signed in: send them to sign in first.
	if (!locals.userData) redirect(302, "/api/auth/google?callbackURL=/account");
	return { email: locals.userData.email };
};

Sign out

Link to /api/auth/signout to delete the session and its cookie and go back to /. Add callbackURL to go back to a page on your site instead. The route reads the session cookie itself, so sign out works even without the hook.

+page.svelte
<a href="/api/auth/signout?callbackURL=/account">Sign out</a>

Sessions

A session lasts 30 days. The cookie holds a random token, and MongoDB stores only its SHA-256 hash as the session _id, so a leaked database cannot be used to sign in. When a session has less than 15 days left, the hook moves its expiry 30 days from now and updates the cookie, so active users stay signed in. Expired sessions, and sessions whose user was deleted, are removed on the next request. Auth cookies are httpOnly, and outside the dev server they are only sent over HTTPS.

Change both times, in milliseconds, where the provider creates its instance.

src/lib/server/auth/google.ts
const DAY = 1000 * 60 * 60 * 24;

export const googleAuth = new GoogleAuth({ expiresIn: DAY * 7, refreshWithin: DAY * 2 });

Add a provider

Install another provider item to offer more than one sign in button. All providers share the session cookie and the user collection, and users keep their account across providers that return the same email, since the callback routes match users by email.

pnx remote0 add https://plainsv.com/r/auth-github.json

Update

Run the install command again to update auth. The CLI asks before it overwrites each file that already exists, and overwriting replaces your changes with the registry version. If you changed the callback endpoint, such as src/routes/api/auth/google/callback/+server.ts, skip that file when the CLI asks to overwrite it, or your changes are lost.

pnx remote0 add https://plainsv.com/r/auth-google.json

Files

The auth code lives in src/lib/server/auth, and the routes live in src/routes/api/auth.

  • Find the AuthSession base class with sessions, cookies, and the hook in session.ts
  • Find each provider class in google.ts, github.ts, and vercel.ts
  • Find the sign in and callback endpoints for each provider in src/routes/api/auth/google, src/routes/api/auth/github, and src/routes/api/auth/vercel
  • Find the shared signout endpoint in src/routes/api/auth/signout

API

src/lib/server/auth/session.ts
/** Shared session methods that every provider class extends */
class AuthSession {
	constructor(options?: { expiresIn?: number; refreshWithin?: number });
	/** Load the session and user from the `session` cookie into `locals` */
	hook: Handle;
	/** Create session token */
	generateSessionToken(): string;
	/** Create session */
	createSession(token: string, userID: string): Promise<DbCollectionsSchema["session"]>;
	/** Set a cookie that page scripts cannot read and that expires at `expiresAt` */
	setCookie(event: RequestEvent, name: string, value: string, expiresAt: Date): void;
	/** Set session to cookies */
	setSessionTokenCookie(event: RequestEvent, token: string, expiresAt: Date): void;
	/** Delete session token from cookies */
	deleteSessionTokenCookie(event: RequestEvent): void;
	/** Validate user session, refreshing it when it expires within `refreshWithin` */
	validateSessionToken(event: RequestEvent, token: string): Promise<SessionValidationResult>;
	/** Delete session from database */
	invalidateSession(sessionId: string): Promise<void>;
}

/** Session methods without a provider, for code every provider shares, such as the sign out route */
const auth: AuthSession;

/** Verified profile every provider's `getUser` returns */
interface AuthUserProfile {
	id: string;
	email: string;
	image: string;
}
src/lib/server/auth/google.ts
const googleAuth: AuthSession & {
	createAuthorizationURL(state: string, codeVerifier: string, scopes: string[], redirectURI: string): URL;
	validateAuthorizationCode(code: string, codeVerifier: string, redirectURI: string): Promise<{ accessToken: string; accessTokenExpiresAt: Date; scopes: string[]; claims: GoogleClaims }>;
	/** Reads the profile from the ID token claims, without another request */
	getUser(tokens: { claims: GoogleClaims }): Promise<AuthUserProfile>;
};
src/lib/server/auth/github.ts
const githubAuth: AuthSession & {
	createAuthorizationURL(state: string, scopes: string[], redirectURI?: string): URL;
	validateAuthorizationCode(code: string): Promise<{ accessToken: string; scopes: string[] }>;
	/** Loads the profile and primary verified email from the GitHub API */
	getUser(tokens: { accessToken: string }): Promise<AuthUserProfile>;
};
src/lib/server/auth/vercel.ts
const vercelAuth: AuthSession & {
	createAuthorizationURL(state: string, codeVerifier: string, scopes: string[], redirectURI: string): URL;
	validateAuthorizationCode(code: string, codeVerifier: string, redirectURI: string): Promise<{ accessToken: string; accessTokenExpiresAt: Date; scopes: string[] }>;
	/** Loads the profile from the UserInfo endpoint */
	getUser(tokens: { accessToken: string }): Promise<AuthUserProfile>;
};