Skip to main content

Overview

logto-authkit provides flexible server authentication utilities that work with Express.js, Next.js, and any Node.js environment. All authentication functions verify JWT tokens issued by your Logto server and provide a consistent AuthContext object.

Key Features

Express Middleware

Ready-to-use middleware for Express.js applications

Next.js Integration

Server-side authentication for Next.js API routes and middleware

Generic Usage

Flexible verifyAuth function for any Node.js environment

Guest Mode

Optional guest mode for unauthenticated users

Authentication Flow

All server authentication functions follow this flow:
  1. Token Extraction: Checks for JWT token in cookies (default: logto_authtoken) or Authorization header
  2. JWKS Fetching: Retrieves public keys from your Logto server (with 5-minute caching)
  3. Signature Verification: Verifies JWT signature using the appropriate public key
  4. Claims Validation: Validates issuer, audience, expiration, and required scopes
  5. Context Creation: Returns an AuthContext object with user information

AuthContext Object

All authentication functions return or set an AuthContext object:
interface AuthContext {
  userId: string | null          // Logto user ID (sub claim)
  isAuthenticated: boolean       // Whether user is authenticated
  payload: AuthPayload | null    // Full JWT payload
  isGuest?: boolean             // Whether user is in guest mode
  guestId?: string              // Generated UUID for guest users
}

Configuration Options

All authentication functions accept a VerifyAuthOptions object:
logtoUrl
string
required
Your Logto server URL (e.g., https://your-tenant.logto.app)
audience
string
required
The API resource identifier registered in Logto
Name of the cookie containing the JWT token
requiredScope
string
Optional scope that must be present in the token
allowGuest
boolean
default:"false"
Enable guest mode for unauthenticated users. When enabled, failed authentication returns a guest context instead of throwing an error.

Guest Mode

When allowGuest is enabled, the authentication functions handle unauthenticated users gracefully:
  • No token found: Returns guest context with generated guestId
  • Invalid token: Falls back to guest context
  • Guest ID stored in cookie: guest_logto_authtoken (auto-generated UUID)
// Example guest context
{
  userId: null,
  isAuthenticated: false,
  payload: null,
  isGuest: true,
  guestId: "550e8400-e29b-41d4-a716-446655440000"
}
Guest mode is useful for applications that support both authenticated and anonymous users, such as e-commerce sites or content platforms.

Token Sources

Authentication tokens can be provided in two ways (checked in order): Set by the frontend authentication SDK:
Cookie: logto_authtoken=eyJhbGciOiJSUzI1NiIs...

2. Authorization Header

Useful for API clients and mobile apps:
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...

Error Handling

Authentication functions throw errors in these scenarios:
  • No token found: When allowGuest is disabled and no token is present
  • Invalid JWT format: Malformed token structure
  • Signature verification failed: Token signature doesn’t match public key
  • Token expired: Token’s exp claim is in the past
  • Invalid issuer: Token wasn’t issued by your Logto server
  • Invalid audience: Token’s aud claim doesn’t match your API resource
  • Missing scope: Required scope not present in token
Always handle authentication errors appropriately in production. Return 401 status codes for authentication failures.

Security Features

Public keys are cached for 5 minutes to reduce load on your Logto server while maintaining security. The cache is automatically refreshed when expired.
All JWT claims are validated including issuer, audience, expiration (exp), not-before (nbf), and custom scopes.
Supports both cookie-based (for web apps) and header-based (for APIs) authentication in the same endpoint.

Next Steps

Express Setup

Add middleware to Express routes

Next.js Setup

Protect Next.js API routes

Generic Usage

Use in any Node.js environment