Core Concepts
Middleware
Intercept and modify requests before they reach your route handlers with an async-first pipeline.
Authentication
Protect routes with auth middleware
Rate Limiting
Built-in rate limiting protection
Logging
Request logging with timing
CORS
Cross-origin configuration
Creating Middleware
Middleware functions receive request, response, and next.
middleware.ts
1import { CanxRequest, CanxResponse, NextFunction } from "canxjs";23const myMiddleware = async (4req: CanxRequest,5res: CanxResponse,6next: NextFunction7) => {8console.log("Request started:", req.method, req.path);9const result = await next();10console.log("Request completed");11return result;12};
Applying Middleware
Apply globally, to specific routes, or route groups.
app.ts
1import { createApp, logger, cors } from "canxjs";23const app = createApp({ port: 3000 });45// Global middleware6app.use(logger());7app.use(cors());89// Route-specific middleware10app.get("/admin", authMiddleware, adminHandler);1112// Group middleware13app.group("/api", (router) => {14router.middleware(authMiddleware);15router.get("/profile", profileHandler);16});
Authentication Middleware
auth.ts
1export const authMiddleware = async (req, res, next) => {2const token = req.header("authorization")?.replace("Bearer ", "");34if (!token) {5return res.status(401).json({ error: "Unauthorized" });6}78try {9const user = await verifyToken(token);10req.context.set("user", user);11return next();12} catch (error) {13return res.status(401).json({ error: "Invalid token" });14}15};
Built-in Middleware
| Middleware | Description |
|---|---|
| logger() | Logs request details |
| cors(opts) | CORS configuration |
| rateLimit(opts) | Rate limit by IP |
| compress() | Gzip compression |
app.ts
1import { createApp, logger, cors, rateLimit, compress } from "canxjs";23const app = createApp({ port: 3000 });45app.use(logger()); // Logs: [2024-01-15] GET /api/users - 12ms67app.use(cors({8origin: ["https://example.com"],9credentials: true10}));1112app.use(rateLimit({ windowMs: 60000, max: 100 }));1314app.use(compress());
Error Handling
errorHandler.ts
1const errorHandler = async (req, res, next) => {2try {3return await next();4} catch (error) {5console.error("[Error]", error);6return res.status(500).json({ error: "Internal server error" });7}8};910app.use(errorHandler);