Routing and Middleware Documentation

Complete guide to routing and middleware in CatCMS using the Hono framework, optimized for Cloudflare Workers. [object Object]

Overview

CatCMS uses Hono, a lightweight web framework optimized for Cloudflare Workers. The middleware pipeline processes every request through a series of layers before reaching route handlers.

Key Concepts

  • Middleware - Functions that execute before route handlers to process requests
  • Middleware Ordering - Order matters - middleware executes in the sequence it’s registered
  • Route Protection - Middleware can protect routes based on authentication, roles, and permissions
  • Context Object - Middleware can set values on the context (c.set()) for downstream use
πŸ”

Authentication

JWT-based auth with KV caching

πŸ›‘οΈ

Authorization

Fine-grained permission system

πŸš€

Bootstrap

System initialization on startup

πŸ“

Logging

Request/response/security logging

⚑

Performance

Caching and security headers

πŸ”Œ

Plugin Middleware

Route protection by plugin status


Middleware Pipeline

The middleware pipeline executes in the following order for every request:

Middleware Configuration

Middleware Execution Order

Request
  ↓
Bootstrap Middleware β†’ Check/run system initialization
  ↓
Logging Middleware β†’ Log request start
  ↓
Security Logging β†’ Check for suspicious patterns
  ↓
Performance Logging β†’ Track request timing
  ↓
Standard Middleware β†’ CORS, security headers, etc.
  ↓
Route-specific Middleware β†’ Auth, roles, permissions
  ↓
Route Handler β†’ Execute business logic
  ↓
Logging Middleware β†’ Log request completion
  ↓
Response

Authentication Middleware

The authentication system uses JWT tokens stored in HTTP-only cookies.

Authentication Manager

Auth Manager

requireAuth Middleware

Requires valid authentication to access a route.

Require Auth

How it works:

  1. Checks for token in Authorization header (Bearer token)
  2. Falls back to auth_token cookie if no header present
  3. Verifies token with KV cache (5-minute TTL)
  4. Falls back to JWT verification if not cached
  5. Sets user object on context for downstream use
  6. Returns 401 error or redirects to login if invalid

requireRole Middleware

Requires specific role(s) to access a route.

Role-Based Access

Role Hierarchy:

  • admin - Full system access
  • editor - Content management and publishing
  • viewer - Read-only access

optionalAuth Middleware

Allows authenticated and unauthenticated access, but populates user if authenticated.

Optional Auth


Authorization and Permissions

Fine-grained permission system for controlling access to specific resources.

Permission Manager

Permission Manager

requirePermission Middleware

Requires specific permission to access a route.

Permission-Based Access

Permission Naming Convention

Permissions follow the pattern: resource.action

Common Permissions:

  • content.create - Create content
  • content.edit - Edit content
  • content.publish - Publish content
  • content.delete - Delete content
  • users.create - Create users
  • users.edit - Edit users
  • users.delete - Delete users
  • media.upload - Upload media files
  • media.delete - Delete media files

Bootstrap Middleware

Handles system initialization on worker startup.

Purpose

The bootstrap middleware runs once per Cloudflare Worker instance to:

  1. Run pending database migrations
  2. Sync collection configurations
  3. Bootstrap core plugins
  4. Install demo plugins (development only)

Bootstrap Middleware

Implementation

Bootstrap Process


Logging Middleware

Comprehensive request/response logging with security monitoring.

Standard Logging Middleware

Logs all HTTP requests and responses.

Logging

What it logs:

  • Request method, URL, and headers
  • Response status code
  • Request duration
  • User ID (if authenticated)
  • IP address and user agent
  • Request ID (generated UUID)

Security Logging Middleware

Monitors suspicious activity and security events.

Security Logging

What it monitors:

  • Suspicious request patterns (SQL injection, XSS attempts)
  • Authentication failures
  • Admin area access
  • Unauthorized access attempts

Suspicious patterns detected:

const suspiciousPatterns = [
  /script[^>]*>/i, // XSS attempts
  /javascript:/i, // JavaScript protocol
  /on\w+\s*=/i, // Event handlers
  /\.\.\/\.\.\//, // Directory traversal
  /\/etc\/passwd/i, // System file access
  /union\s+select/i, // SQL injection
  /drop\s+table/i, // SQL injection
]

Performance Logging Middleware

Tracks slow requests for performance monitoring.

Performance Logging


Performance Middleware

Middleware for caching, compression, and security headers.

Cache Headers Middleware

Adds cache-control headers to responses.

Cache Headers

How it works:

  • Only caches successful HTML responses (200 status)
  • Sets Cache-Control: private, max-age={maxAge}
  • Private caching prevents CDN caching of authenticated pages

Security Headers Middleware

Adds security headers to all responses.

Security Headers

Headers added:

'X-Content-Type-Options': 'nosniff'
'X-Frame-Options': 'SAMEORIGIN'
'X-XSS-Protection': '1; mode=block'

Plugin Middleware

Controls access to plugin routes based on plugin activation status.

requireActivePlugin Middleware

Ensures a plugin is active before allowing access to its routes.

Plugin Middleware

How it works:

  1. Queries database for plugin status
  2. Returns 404 with user-friendly message if plugin is not active
  3. Allows request to continue if plugin is active
  4. Fails open (allows access) if database query fails

Route Structure

CatCMS organizes routes into logical modules.

Public Routes

No authentication required.

Public Routes

Admin Routes

Requires authentication + admin or editor role.

Admin Routes


Creating Custom Middleware

You can create custom middleware to add specific functionality to your CatCMS application.

Basic Middleware Structure

Middleware Template

Example: Rate Limiting Middleware

Rate Limiter

Middleware Best Practices

  • Keep middleware focused on a single responsibility - Minimize database queries in middleware - Use context variables to pass data between middleware - Handle errors gracefully and provide meaningful error messages - Consider performance impact of middleware execution order - Test middleware independently before integrating

Next Steps

Was this page helpful?