Skip to main content

signToken()

Creates a signed JWT token for a user session.
payload
SessionData
required
The session data to encode in the token
return
Promise<string>
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.
input
string
required
The JWT token string to verify
return
Promise<SessionData>
A promise that resolves to the decoded session data

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

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.
user
NewUser
required
The user object to create a session for
return
Promise<void>
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;
};

Build docs developers (and LLMs) love