Skip to content

Middleware

Yelix provides enhanced middleware handling with named middleware support, execution time tracking, and better debugging capabilities.

You can use middleware just like in Hono:

import { YelixHono } from "@yelix/hono";
const app = new YelixHono();
// Global middleware
app.use("*", async (c, next) => {
console.log("Global middleware executed");
await next();
});
// Path-specific middleware
app.use("/api/*", async (c, next) => {
// Only applies to /api/* routes
await next();
});

Named middleware provides better tracking, logging, and debugging. Use the namedMiddleware function to create middleware with a name:

import { YelixHono, namedMiddleware } from "@yelix/hono";
const app = new YelixHono();
// Create a named middleware
const loggerMiddleware = namedMiddleware("logger", async (c, next) => {
app.yelixLog(c, "Logger middleware executed");
await next();
});
// Use the named middleware
app.use(loggerMiddleware);
  1. Better tracking: Named middleware appears in the dashboard with its name
  2. Execution time: Track how long each middleware takes to execute
  3. Logging: Logs are associated with the middleware name
  4. Debugging: Easier to identify which middleware is causing issues
import { YelixHono, namedMiddleware } from "@yelix/hono";
const app = new YelixHono();
// Create named middleware
const authMiddleware = namedMiddleware("auth", async (c, next) => {
const token = c.req.header("Authorization");
if (!token) {
return c.json({ error: "Unauthorized" }, 401);
}
app.yelixLog(c, "Authentication successful");
await next();
});
const rateLimitMiddleware = namedMiddleware("rate-limit", async (c, next) => {
// Rate limiting logic
app.yelixLog(c, "Rate limit check passed");
await next();
});
// Apply to specific routes
app.get(
"/api/protected",
authMiddleware,
rateLimitMiddleware,
(c) => {
return c.json({ message: "Protected resource" });
}
);

You can attach metadata to named middleware for additional context:

import { YelixHono, namedMiddleware } from "@yelix/hono";
const app = new YelixHono();
const customMiddleware = namedMiddleware(
"custom-middleware",
async (c, next) => {
await next();
},
{
version: "1.0.0",
description: "Custom middleware for API",
// Any custom metadata
}
);
app.use(customMiddleware);

Use yelixLog() to log messages from your middleware:

import { YelixHono, namedMiddleware } from "@yelix/hono";
const app = new YelixHono();
const loggerMiddleware = namedMiddleware("request-logger", async (c, next) => {
const start = Date.now();
app.yelixLog(c, "Request started", {
method: c.req.method,
path: c.req.path,
});
await next();
const duration = Date.now() - start;
app.yelixLog(c, "Request completed", {
duration: `${duration}ms`,
status: c.res.status,
});
});
app.use(loggerMiddleware);
import { YelixHono, namedMiddleware } from "@yelix/hono";
const app = new YelixHono();
// Create multiple named middleware
const corsMiddleware = namedMiddleware("cors", async (c, next) => {
c.header("Access-Control-Allow-Origin", "*");
c.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
app.yelixLog(c, "CORS headers set");
await next();
});
const timingMiddleware = namedMiddleware("timing", async (c, next) => {
const start = Date.now();
await next();
const duration = Date.now() - start;
app.yelixLog(c, `Request took ${duration}ms`);
});
const authMiddleware = namedMiddleware("auth", async (c, next) => {
const apiKey = c.req.header("X-API-Key");
if (apiKey !== "secret-key") {
return c.json({ error: "Invalid API key" }, 401);
}
app.yelixLog(c, "Authentication successful");
await next();
});
// Apply middleware
app.use(corsMiddleware);
app.use(timingMiddleware);
// Apply auth only to API routes
app.use("/api/*", authMiddleware);
// Routes
app.get("/", (c) => {
return c.json({ message: "Hello!" });
});
app.get("/api/data", (c) => {
return c.json({ data: "Protected data" });
});
Deno.serve({ port: 8000 }, app.fetch);

Middleware executes in the order they are added:

app.use(middleware1); // Executes first
app.use(middleware2); // Executes second
app.use(middleware3); // Executes third
app.get("/route", handler); // Handler executes last

When using multiple middleware on a route:

app.get(
"/route",
middleware1, // Executes first
middleware2, // Executes second
middleware3, // Executes third
handler // Handler executes last
);
  1. Use named middleware for better debugging and monitoring
  2. Log important events using yelixLog() for dashboard visibility
  3. Keep middleware focused - each middleware should do one thing
  4. Order matters - place authentication middleware before route handlers
  5. Use path-specific middleware when possible to avoid unnecessary execution