Lucia Auth — Simple Authentication
You are an expert in Lucia, the lightweight authentication library for TypeScript. You help developers implement session-based authentication with email/password, OAuth (Google, GitHub, Discord), magic links, and two-factor authentication — providing a simple, database-agnostic auth layer that you understand and control, without the complexity of full auth platforms.
Core Capabilities
Session Management
// lib/auth.ts
import { Lucia } from "lucia";
import { DrizzlePostgreSQLAdapter } from "@lucia-auth/adapter-drizzle";
import { db } from "./db";
import { users, sessions } from "./db/schema";
const adapter = new DrizzlePostgreSQLAdapter(db, sessions, users);
export const lucia = new Lucia(adapter, {
sessionCookie: {
expires: false, // Session cookie (cleared on browser close)
attributes: { secure: process.env.NODE_ENV === "production" },
},
getUserAttributes: (attributes) => ({
email: attributes.email,
name: attributes.name,
avatarUrl: attributes.avatar_url,
}),
});
// Email/password signup
async function signup(email: string, password: string, name: string) {
const hashedPassword = await new Argon2id().hash(password);
const userId = generateIdFromEntropySize(10);
await db.insert(users).values({
id: userId,
email,
name,
hashedPassword,
});
const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
return sessionCookie; // Set as response cookie
}
// Login
async function login(email: string, password: string) {
const user = await db.query.users.findFirst({ where: eq(users.email, email) });
if (!user) throw new Error("Invalid credentials");
const valid = await new Argon2id().verify(user.hashedPassword, password);
if (!valid) throw new Error("Invalid credentials");
const session = await lucia.createSession(user.id, {});
return lucia.createSessionCookie(session.id);
}
// Validate session (middleware)
async function validateRequest(request: Request) {
const cookieHeader = request.headers.get("Cookie");
const sessionId = lucia.readSessionCookie(cookieHeader ?? "");
if (!sessionId) return { user: null, session: null };
const result = await lucia.validateSession(sessionId);
return result; // { user, session } or { user: null, session: null }
}
// Logout
async function logout(sessionId: string) {
await lucia.invalidateSession(sessionId);
return lucia.createBlankSessionCookie();
}
OAuth (Google)
import { Google } from "arctic";
const google = new Google(
process.env.GOOGLE_CLIENT_ID!,
process.env.GOOGLE_CLIENT_SECRET!,
"https://myapp.com/auth/google/callback",
);
// Redirect to Google
app.get("/auth/google", async (c) => {
const [url, codeVerifier, state] = await google.createAuthorizationURL();
// Store codeVerifier and state in cookie
return c.redirect(url.toString());
});
// Handle callback
app.get("/auth/google/callback", async (c) => {
const { code, state } = c.req.query();
const tokens = await google.validateAuthorizationCode(code, codeVerifier);
const googleUser = await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {
headers: { Authorization: `Bearer ${tokens.accessToken()}` },
}).then(r => r.json());
// Find or create user
let user = await db.query.users.findFirst({ where: eq(users.email, googleUser.email) });
if (!user) {
const userId = generateIdFromEntropySize(10);
[user] = await db.insert(users).values({
id: userId, email: googleUser.email, name: googleUser.name, avatar_url: googleUser.picture,
}).returning();
}
const session = await lucia.createSession(user.id, {});
const cookie = lucia.createSessionCookie(session.id);
return c.redirect("/dashboard", { headers: { "Set-Cookie": cookie.serialize() } });
});
Installation
npm install lucia arctic # Lucia + OAuth helpers
npm install @lucia-auth/adapter-drizzle # Or adapter-prisma, adapter-mongoose, etc.
npm install @node-rs/argon2 # Password hashing
Best Practices
- Session-based — Lucia uses server-side sessions + cookies; more secure than JWT for web apps
- Database-agnostic — Adapters for Drizzle, Prisma, Mongoose, better-sqlite3, Turso, etc.
- Arctic for OAuth — Use
arctic library for OAuth providers; handles PKCE, state, tokens
- Argon2 for passwords — Use
@node-rs/argon2 for hashing; industry standard, timing-safe
- Cookie security — Set
secure: true in production; httpOnly is automatic
- Session validation — Call
validateSession() on every request; auto-extends session expiry
- Invalidation —
invalidateSession for logout; invalidateUserSessions for security reset
- No magic — Lucia is explicit; you write the signup/login/oauth flows; you understand every line
1---2name: lucia-auth3description: >-4 You are an expert in Lucia, the lightweight authentication library for5 TypeScript. You help developers implement session-based authentication with6 email/password, OAuth (Google, GitHub, Discord), magic links, and two-factor7 authentication — providing a simple, database-agnostic auth layer that you8 understand and control, without the complexity of full auth platforms.9license: Apache-2.010compatibility: ''11metadata:12 source: https://skillmd.com/skills/eliferjunior/lucia-auth13 author: terminal-skills14 version: 1.0.015 category: Backend Development16 tags:17 - authentication18 - sessions19 - oauth20 - typescript21 - auth22 - security23---2425# Lucia Auth — Simple Authentication2627You are an expert in Lucia, the lightweight authentication library for TypeScript. You help developers implement session-based authentication with email/password, OAuth (Google, GitHub, Discord), magic links, and two-factor authentication — providing a simple, database-agnostic auth layer that you understand and control, without the complexity of full auth platforms.2829## Core Capabilities3031### Session Management3233```typescript34// lib/auth.ts35import { Lucia } from "lucia";36import { DrizzlePostgreSQLAdapter } from "@lucia-auth/adapter-drizzle";37import { db } from "./db";38import { users, sessions } from "./db/schema";3940const adapter = new DrizzlePostgreSQLAdapter(db, sessions, users);4142export const lucia = new Lucia(adapter, {43 sessionCookie: {44 expires: false, // Session cookie (cleared on browser close)45 attributes: { secure: process.env.NODE_ENV === "production" },46 },47 getUserAttributes: (attributes) => ({48 email: attributes.email,49 name: attributes.name,50 avatarUrl: attributes.avatar_url,51 }),52});5354// Email/password signup55async function signup(email: string, password: string, name: string) {56 const hashedPassword = await new Argon2id().hash(password);57 const userId = generateIdFromEntropySize(10);5859 await db.insert(users).values({60 id: userId,61 email,62 name,63 hashedPassword,64 });6566 const session = await lucia.createSession(userId, {});67 const sessionCookie = lucia.createSessionCookie(session.id);68 return sessionCookie; // Set as response cookie69}7071// Login72async function login(email: string, password: string) {73 const user = await db.query.users.findFirst({ where: eq(users.email, email) });74 if (!user) throw new Error("Invalid credentials");7576 const valid = await new Argon2id().verify(user.hashedPassword, password);77 if (!valid) throw new Error("Invalid credentials");7879 const session = await lucia.createSession(user.id, {});80 return lucia.createSessionCookie(session.id);81}8283// Validate session (middleware)84async function validateRequest(request: Request) {85 const cookieHeader = request.headers.get("Cookie");86 const sessionId = lucia.readSessionCookie(cookieHeader ?? "");87 if (!sessionId) return { user: null, session: null };8889 const result = await lucia.validateSession(sessionId);90 return result; // { user, session } or { user: null, session: null }91}9293// Logout94async function logout(sessionId: string) {95 await lucia.invalidateSession(sessionId);96 return lucia.createBlankSessionCookie();97}98```99100### OAuth (Google)101102```typescript103import { Google } from "arctic";104105const google = new Google(106 process.env.GOOGLE_CLIENT_ID!,107 process.env.GOOGLE_CLIENT_SECRET!,108 "https://myapp.com/auth/google/callback",109);110111// Redirect to Google112app.get("/auth/google", async (c) => {113 const [url, codeVerifier, state] = await google.createAuthorizationURL();114 // Store codeVerifier and state in cookie115 return c.redirect(url.toString());116});117118// Handle callback119app.get("/auth/google/callback", async (c) => {120 const { code, state } = c.req.query();121 const tokens = await google.validateAuthorizationCode(code, codeVerifier);122 const googleUser = await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {123 headers: { Authorization: `Bearer ${tokens.accessToken()}` },124 }).then(r => r.json());125126 // Find or create user127 let user = await db.query.users.findFirst({ where: eq(users.email, googleUser.email) });128 if (!user) {129 const userId = generateIdFromEntropySize(10);130 [user] = await db.insert(users).values({131 id: userId, email: googleUser.email, name: googleUser.name, avatar_url: googleUser.picture,132 }).returning();133 }134135 const session = await lucia.createSession(user.id, {});136 const cookie = lucia.createSessionCookie(session.id);137 return c.redirect("/dashboard", { headers: { "Set-Cookie": cookie.serialize() } });138});139```140141## Installation142143```bash144npm install lucia arctic # Lucia + OAuth helpers145npm install @lucia-auth/adapter-drizzle # Or adapter-prisma, adapter-mongoose, etc.146npm install @node-rs/argon2 # Password hashing147```148149## Best Practices1501511. **Session-based** — Lucia uses server-side sessions + cookies; more secure than JWT for web apps1522. **Database-agnostic** — Adapters for Drizzle, Prisma, Mongoose, better-sqlite3, Turso, etc.1533. **Arctic for OAuth** — Use `arctic` library for OAuth providers; handles PKCE, state, tokens1544. **Argon2 for passwords** — Use `@node-rs/argon2` for hashing; industry standard, timing-safe1555. **Cookie security** — Set `secure: true` in production; `httpOnly` is automatic1566. **Session validation** — Call `validateSession()` on every request; auto-extends session expiry1577. **Invalidation** — `invalidateSession` for logout; `invalidateUserSessions` for security reset1588. **No magic** — Lucia is explicit; you write the signup/login/oauth flows; you understand every line