signToken()
Creates a signed JWT token for a user session.
The session data to encode in the token
ISO 8601 timestamp indicating when the session expires
A promise that resolves to the signed JWT token string
Function Signature
async function signToken(payload: SessionData): Promise<string>
Implementation Details
- Uses HS256 algorithm for signing
- Sets token expiration to 1 day from issuance
- Uses
AUTH_SECRET environment variable as the signing key
- Automatically sets the issued at (
iat) timestamp
Example
import { signToken } from '@/lib/auth/session';
const sessionData = {
user: { id: 123 },
expires: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
};
const token = await signToken(sessionData);
console.log(token); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
verifyToken()
Verifies and decodes a JWT token, returning the session data.
The JWT token string to verify
A promise that resolves to the decoded session data
ISO 8601 timestamp indicating when the session expires
Function Signature
async function verifyToken(input: string): Promise<SessionData>
Implementation Details
- Validates the token signature using
AUTH_SECRET environment variable
- Only accepts HS256 algorithm
- Throws an error if the token is invalid or expired
Example
import { verifyToken } from '@/lib/auth/session';
try {
const sessionData = await verifyToken(token);
console.log(sessionData.user.id); // 123
} catch (error) {
console.error('Invalid or expired token');
}
getSession()
Retrieves and verifies the current user’s session from cookies.
return
Promise<SessionData | null>
A promise that resolves to the session data if a valid session exists, or null if no session is found
ISO 8601 timestamp indicating when the session expires
Function Signature
async function getSession(): Promise<SessionData | null>
Implementation Details
- Reads the
session cookie value
- Returns
null if no session cookie exists
- Verifies the token and returns the decoded session data
- Must be called in a server component or API route
Example
import { getSession } from '@/lib/auth/session';
export default async function DashboardPage() {
const session = await getSession();
if (!session) {
redirect('/sign-in');
}
return <div>Welcome, user {session.user.id}</div>;
}
setSession()
Creates a new session for a user and stores it in an HTTP-only cookie.
The user object to create a session for
The user’s ID (must be defined)
The user’s hashed password
The user’s name (optional)
The user’s role (defaults to ‘member’)
A promise that resolves when the session cookie is set
Function Signature
async function setSession(user: NewUser): Promise<void>
Implementation Details
- Sets session expiration to 24 hours (1 day) from creation
- Creates a signed JWT token with the user ID and expiration time
- Stores the token in an HTTP-only cookie named
session
- Cookie configuration:
httpOnly: true - Prevents client-side JavaScript access
secure: true - Only sent over HTTPS
sameSite: 'lax' - CSRF protection
expires - Set to match session expiration (24 hours)
Example
import { setSession } from '@/lib/auth/session';
import { getUserByEmail } from '@/lib/db/queries';
import { comparePasswords } from '@/lib/auth/session';
export async function signInAction(email: string, password: string) {
const user = await getUserByEmail(email);
if (!user) {
throw new Error('Invalid credentials');
}
const isValid = await comparePasswords(password, user.passwordHash);
if (!isValid) {
throw new Error('Invalid credentials');
}
await setSession(user);
return { success: true };
}
Type Definitions
type SessionData = {
user: { id: number };
expires: string;
};
type NewUser = {
id?: number;
email: string;
passwordHash: string;
name?: string | null;
role?: string;
createdAt?: Date;
updatedAt?: Date;
deletedAt?: Date | null;
};