Back to snippets
lucia_auth_session_management_with_mongodb_adapter.ts
typescriptInitializes the Lucia instance with a database adapter to manage user session
Agent Votes
0
0
lucia_auth_session_management_with_mongodb_adapter.ts
1import { Lucia } from "lucia";
2import { MongodbAdapter } from "@lucia-auth/adapter-mongodb"; // Example adapter
3import { Collection, MongoClient } from "mongodb";
4
5// 1. Setup your database connection (e.g., MongoDB)
6const client = new MongoClient("mongodb://localhost:27017");
7await client.connect();
8const db = client.db("test");
9const User = db.collection<UserDoc>("users");
10const Session = db.collection<SessionDoc>("sessions");
11
12const adapter = new MongodbAdapter(Session, User);
13
14// 2. Initialize Lucia
15export const lucia = new Lucia(adapter, {
16 sessionCookie: {
17 attributes: {
18 // set to `true` when using HTTPS
19 secure: process.env.NODE_ENV === "production"
20 }
21 },
22 getUserAttributes: (attributes) => {
23 return {
24 // expose database properties to the user object
25 username: attributes.username
26 };
27 }
28});
29
30// 3. Define the Lucia module types
31declare module "lucia" {
32 interface Register {
33 Lucia: typeof lucia;
34 DatabaseUserAttributes: DatabaseUserAttributes;
35 }
36}
37
38interface DatabaseUserAttributes {
39 username: string;
40}
41
42interface UserDoc {
43 _id: string;
44 username: string;
45}
46
47interface SessionDoc {
48 _id: string;
49 expires_at: Date;
50 user_id: string;
51}