Authentication
Swift Rust doesn't ship with an authentication library. It works with any library that uses the standard Fetch Request and Response APIs.
Cookie-based sessions
The simplest pattern. Set a cookie on login, read it on every request.
app/login/route.ts
import type { RouteHandler } from "swift-rust/router";
import { verifyPassword, createSession } from "@/lib/auth";
export const POST: RouteHandler = async ({ request }) => {
const { email, password } = await request.json();
const user = await verifyPassword(email, password);
if (!user) return new Response("Invalid credentials", { status: 401 });
const session = await createSession(user.id);
return new Response(JSON.stringify({ user }), {
headers: {
"Set-Cookie": `session=${session.id}; HttpOnly; SameSite=Lax; Path=/`,
},
});
};Reading the session
app/proxy.ts
import { redirect } from "swift-rust/router";
import type { RouteRequest } from "swift-rust/router";
export default function proxy(ctx: RouteRequest) {
const session = ctx.cookies.get("session");
if (!session) redirect("/login");
}
export const matcher = ["/dashboard/**", "/api/protected/**"];OAuth
For OAuth, redirect the user to the provider's authorization URL, then handle the callback in a route handler.
Recommended libraries
- Lucia — session management
- Auth.js — multi-provider OAuth
- Better Auth — modern TypeScript-first auth