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";
2
3const myMiddleware = async (
4 req: CanxRequest,
5 res: CanxResponse,
6 next: NextFunction
7) => {
8 console.log("Request started:", req.method, req.path);
9 const result = await next();
10 console.log("Request completed");
11 return result;
12};

Applying Middleware

Apply globally, to specific routes, or route groups.

app.ts
1import { createApp, logger, cors } from "canxjs";
2
3const app = createApp({ port: 3000 });
4
5// Global middleware
6app.use(logger());
7app.use(cors());
8
9// Route-specific middleware
10app.get("/admin", authMiddleware, adminHandler);
11
12// Group middleware
13app.group("/api", (router) => {
14 router.middleware(authMiddleware);
15 router.get("/profile", profileHandler);
16});

Authentication Middleware

auth.ts
1export const authMiddleware = async (req, res, next) => {
2 const token = req.header("authorization")?.replace("Bearer ", "");
3
4 if (!token) {
5 return res.status(401).json({ error: "Unauthorized" });
6 }
7
8 try {
9 const user = await verifyToken(token);
10 req.context.set("user", user);
11 return next();
12 } catch (error) {
13 return res.status(401).json({ error: "Invalid token" });
14 }
15};

Built-in Middleware

MiddlewareDescription
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";
2
3const app = createApp({ port: 3000 });
4
5app.use(logger()); // Logs: [2024-01-15] GET /api/users - 12ms
6
7app.use(cors({
8 origin: ["https://example.com"],
9 credentials: true
10}));
11
12app.use(rateLimit({ windowMs: 60000, max: 100 }));
13
14app.use(compress());

Error Handling

errorHandler.ts
1const errorHandler = async (req, res, next) => {
2 try {
3 return await next();
4 } catch (error) {
5 console.error("[Error]", error);
6 return res.status(500).json({ error: "Internal server error" });
7 }
8};
9
10app.use(errorHandler);

Next Steps

Learn about Request and Response objects.