Auth

createKey()#

Creates a new key for a user.

const createKey: (options: {
	userId: string;
	providerId: string;
	providerUserId: string;
	password: string | null;
}) => Promise<Key>;
Parameters#
nametypedescription
options.userIdstringThe user id of the key to create
options.providerIdstringThe provider id of the key
options.providerUserIdstringThe provider user id of the key
options.passwordstring | nullThe password for the key
Returns#
typedescription
KeyA new key
Errors#
name
AUTH_INVALID_USER_ID
AUTH_DUPLICATE_KEY_ID

Example#

import { auth } from "./lucia.js";

const key = await auth.createKey({
	userId,
	providerId: "email",
	providerUserId: "[email protected]",
	password: "123456"
});

const key = await auth.createKey({
	userId,
	providerId: "github",
	providerUserId: githubUserId,
	password: null
});

createSession()#

Creates a new session for a user.

const createSession: (options: {
	userId: string;
	attributes: Lucia.DatabaseSessionAttributes;
}) => Promise<Session>;
Parameters#
nametypedescription
options.userIdstringThe user id of the session to create
options.attributesLucia.DatabaseSessionAttributesDatabase session attributes
Returns#
typedescription
SessionA new session
Errors#
name
AUTH_INVALID_USER_ID

Example#

import { auth } from "./lucia.js";

const session = await auth.createSession({
	userId,
	attributes: {
		created_at: new Date()
	}
});

createSessionCookie()#

Creates a session in the form of Cookie. Returns a blank session cookie that will override the existing cookie and clears them if null is provided as parameter session.

const createSessionCookie: (session: Session | null) => Cookie;
Parameters#
nametypedescription
sessionSession | nullSession to create a cookie for
Returns#
typedescription
CookieSession cookie

Example#

import { auth } from "./lucia.js";

const sessionCookie = auth.createSessionCookie(session);
const response = new Response(null, {
	headers: {
		"Set-Cookie": sessionCookie.serialize()
	}
});

createUser()#

Creates a new user, with an option to create a key alongside the user.

const createUser: (options: {
	key: {
		providerId: string;
		providerUserId: string;
		password: string | null;
	} | null;
	attributes: Lucia.UserAttributes;
	userId?: string;
}) => Promise<User>;
Parameters#
nametypeoptionaldescription
options.keynull | Record<string, any>If defined, the key will be created alongside the user
options.key?.providerIdstringKey provider id
options.key?.providerUserIdstringKey provider user id
options.key?.passwordstringKey password
options.attributesLucia.DatabaseUserAttributesDatabase user attributes
userIdstringCustom user id
Returns
typedescription
UserA new user
Errors#
name
AUTH_DUPLICATE_KEY_ID

Example#

import { auth } from "./lucia.js";

const user = await auth.createUser({
	key: {
		providerId: "email",
		providerUserId: "[email protected]",
		password: "123456"
	},
	attributes: {
		username: "user123",
		admin: true
	}
});

deleteDeadUserSessions()#

Deletes all sessions that are expired and their idle period has passed (dead sessions). Will succeed regardless of the validity of the user id.

const deleteDeadUserSessions: (userId: string) => Promise<void>;
Parameters#
nametypedescription
userIdstringUser id

Example#

import { auth } from "./lucia.js";

await auth.deleteExpiredUserSession(userId);

deleteKey()#

Deletes a key. Will succeed regardless of the validity of the key id.

const deleteKey: (providerId: string, providerUserId: string) => Promise<void>;
Parameters#
nametypedescription
providerIdstringThe provider id of the key
providerUserIdstringThe provider user id of the key

Example#

import { auth } from "./lucia.js";

await auth.deleteKey("username", "[email protected]");

deleteUser()#

Deletes a user. Will succeed regardless of the validity of the user id.

const deleteUser: (userId: string) => Promise<void>;
Parameters#
nametypedescription
userIdstringA user id to delete

Example#

import { auth } from "./lucia.js";

await auth.deleteUser(userId);

getAllUserKeys()#

Validates the user id and returns all keys of a user.

const getAllUserKeys: (userId: string) => Promise<Key[]>;
Parameters#
nametypedescription
userIdstringThe A user id
Returns#
type
Key[]
Errors#
name
AUTH_INVALID_USER_ID

Example#

import { auth } from "./lucia.js";

const keys = await auth.getAllUserKeys(userId);

getAllUserSessions()#

Validate the user id and get all valid sessions of a user. Includes active and idle sessions, but not dead sessions.

const getAllUserSessions: (userId: string) => Promise<Session[]>;
Parameters#
nametypedescription
userIdstringThe A user id
Returns#
type
Session[]
Errors#
name
AUTH_INVALID_USER_ID

Example#

import { auth } from "./lucia.js";

try {
	const sessions = await auth.getAllUserSessions(userId);
} catch {
	// invalid user id
}

getKey()#

Gets a key. Use `Auth.useKey() method for validating key passwords.

const getKey: (providerId: string, providerUserId: string) => Promise<Key>;
Parameters#
nametypedescription
providerIdstringThe provider id of the key
providerUserIdstringThe provider user id of the key
Returns#
type
Key
Errors#
name
AUTH_INVALID_KEY_ID

Example#

import { auth } from "./lucia.js";

const key = await auth.getKey("email", "[email protected]");

getSession()#

Gets a session. Returns both active and idle sessions.

const getSessionUser: (sessionId: string) => Promise<Session>;
Parameters#
nametypedescription
sessionIdstringAn active or idle session id
Returns#
type
Session
Errors#
name
AUTH_INVALID_SESSION_ID

Example#

import { auth } from "./lucia.js";

const session = await auth.getSession(sessionId);
if (session.state === "active") {
	// valid session
}
if (session.state === "idle") {
	// should be reset
}

getUser()#

Gets a user.

const getUser: (userId: string) => Promise<User>;
Parameters#
nametypedescription
userIdstringA user id
Returns#
type
User
Errors#
name
AUTH_INVALID_USER_ID

Example#

import { auth } from "./lucia.js";

const user = await auth.getUser(userId);

handleRequest()#

Creates a new Auth instance.

const handleRequest: (...args: any[]) => AuthRequest;
Parameters#
typedescription
any[]Refer to the middleware’s documentation
Returns#

invalidateAllUserSessions()#

Invalidates all sessions of a user. Will succeed regardless of the validity of the user id.

const invalidateAllUserSessions: (userId: string) => Promise<void>;
Parameters#
nametypedescription
userIdstringA user id

Example#

import { auth } from "./lucia.js";

await auth.invalidateAllUserSession(userId);

invalidateSession()#

Invalidates a session. Will succeed regardless of the validity of the session id.

const invalidateSession: (sessionId: string) => Promise<void>;
Parameters#
nametypedescription
sessionIdstringA session id

Example#

import { auth } from "./lucia.js";

await auth.invalidateSession(sessionId);

readBearerToken()#

Takes a Authorization request header and returns the bearer token if it exists. This does not validate the session. Bearer token must be stored in the following format:

Authorization: Bearer <session_id>
const readBearerToken: (
	authorizationHeader: string | null | undefined
) => string | null;
Parameters#
nametypedescription
authorizationHeaderstring | null | undefinedAuthorization header
Returns#
typedescription
stringBearer token value
nullBearer token does not exist

Example#

import { auth } from "./lucia.js";

const sessionId = auth.readBearerToken(
	"Bearer CAbc9LAUY3Q18f0s92Jo817dna8eDtmRrUrDuVFM"
);

readSessionCookie()#

Takes a Cookie request header and returns the session cookie value if it exists. This does not validate the session.

const readSessionCookie: (
	cookieHeader: string | null | undefined
) => string | null;
Parameters#
nametypedescription
cookieHeaderstring | null | undefinedCookie header
Returns#
typedescription
stringSession cookie value
nullSession cookie does not exist

Example#

import { auth } from "./lucia.js";

const sessionId = auth.readSessionCookie(
	"auth_session=CAbc9LAUY3Q18f0s92Jo817dna8eDtmRrUrDuVFM"
);

transformDatabaseKey()#

Transforms key object returned from database query into Lucia’s Key.

const transformDatabaseKey: (databaseKey: KeySchema) => Key;
Parameters#
nametypedescription
databaseKeyKeySchemaRaw key object
Returns#
type
Key

Example#

import { createKeyId } from "lucia";
import { auth } from "./lucia.js";

const databaseKey = await db.getKey(createKeyId(providerId, providerUserId));
const key = auth.transformDatabaseKey(databaseKey);

transformDatabaseSession()#

Transforms session object returned from database query into Lucia’s Session.

const transformDatabaseSession: (
	databaseSession: SessionSchema,
	context: {
		user: User;
		fresh: boolean;
	}
) => Session;
Parameters#
nametypedescription
databaseSessionSessionSchemaRaw session object
context.userUserSession.user
context.freshbooleanSession.fresh
Returns#
type
Session

Example#

import { auth } from "./lucia.js";

const databaseUser = await db.getUser(userId);
const databaseSession = await db.getSession(sessionId);
const session = auth.transformDatabaseSession(databaseSession, {
	user: auth.transformDatabaseUser(databaseUser),
	fresh: false
});

transformDatabaseUser()#

Transforms user object returned from database query into Lucia’s User.

const transformDatabaseUser: (databaseUser: UserSchema) => User;
Parameters#
nametypedescription
databaseUserUserSchemaRaw user object
Returns#
type
User

Example#

import { auth } from "./lucia.js";

const databaseUser = await db.getUser(userId);
const user = auth.transformDatabaseUser(databaseUser);

updateKeyPassword()#

Updates the password of a key. Pass null to parameter password to remove the key’s password.

const updateKeyPassword: (
	providerId: string,
	providerUserId: string,
	password: string | null
) => Promise<Key>;
Parameters#
nametypedescription
providerIdstringThe provider id of the target key
providerUserIdstringThe provider user id of the target key
passwordstring | nullA new password
Returns#
typedescription
Keyupdated key
Errors#
name
AUTH_INVALID_KEY_ID

Example#

import { auth } from "./lucia.js";

await auth.updateKeyPassword("email", "[email protected]", "123456");
await auth.updateKeyPassword("email", "[email protected]", null); // remove password

updateSessionAttributes()#

Updates one or more fields of a session. Values of parameter attributes can be null but not undefined.

const updateSessionAttributes: (
	sessionId: string,
	attributes: Partial<Lucia.DatabaseSessionAttributes>
) => Promise<Session>;
Parameters#
nametypedescription
sessionIdstringA session id
attributesPartial<Lucia.DatabaseSessionAttributes>session fields to update
Returns#
typedescription
SessionThe updated session
Errors#
name
AUTH_INVALID_SESSION_ID

Example#

import { auth } from "./lucia.js";

await auth.updateUserAttributes(userId, {
	username: "user123",
	profile_image: null
});

updateUserAttributes()#

Updates one or more database fields of a user. Values of parameter attributes can be null but not undefined.

const updateUserAttributes: (
	userId: string,
	attributes: Partial<Lucia.DatabaseUserAttributes>
) => Promise<User>;
Parameters#
nametypedescription
userIdstringA user id
attributesPartial<Lucia.DatabaseUserAttributes>user fields to update
Returns#
typedescription
UserThe updated user
Errors#
name
AUTH_INVALID_USER_ID

Example#

import { auth } from "./lucia.js";

await auth.updateUserAttributes(userId, {
	username: "user123",
	profile_image: null
});

useKey()#

Validates a key, including the password. null must be passed to parameter password if the password does not hold a password.

const useKey: (
	providerId: string,
	providerUserId: string,
	password: string | null
) => Promise<Key>;
Parameters#
nametypedescription
providerIdstringThe provider id of the key
providerUserIdstringThe provider user id of the key
passwordstring | nullThe password of the key
Returns#
typedescription
KeyThe validated key
Errors#
name
AUTH_INVALID_KEY_ID
AUTH_INVALID_PASSWORD
AUTH_OUTDATED_PASSWORD

Example#

import { auth } from "./lucia.js";

const key = await auth.useKey("email", "[email protected]", "123456");
const key = await auth.useKey("github", githubUserId, null);

validateRequestOrigin()#

Deprecated: To be removed in the next major release.

Used for CSRF protection. Checks if the request origin is trusted for non-GET and non-HEAD requests (e.g. POST, PUT, DELETE), and throws an error if the origin is invalid. Trusted origins include where the server is hosted and its subdomains defined with csrfProtection.allowedSubdomains configuration.

const validateRequestOrigin: (request: {
	url: string | URL;
	method: string;
	originHeader: string | null;
}) => void;
Parameters#
nametypedescription
request.urlstringThe request url
request.methodstringThe request method (case insensitive)
request.originstring | nullThe request origin header
Errors#
name
AUTH_INVALID_REQUEST

Example#

import { auth } from "./lucia.js";

auth.validateRequestOrigin({
	url: "http://localhost:3000/api",
	method: "POST",
	originHeader: "http://localhost:3000"
});

validateSession()#

Validates a session, resetting it if it’s idle.

const validateSession: (sessionId: string) => Promise<Session>;
Parameters#
nametypedescription
sessionIdstringAn active or idle session id
Returns#
typedescription
SessionThe validated session
Errors#
name
AUTH_INVALID_SESSION_ID

Example#

import { auth } from "./lucia.js";

const session = await auth.validateSession(sessionId);
if (session.fresh) {
	// session was reset
	// extend cookie expiration
}