All posts

Fix Middleware Error in Deno

Resolve middleware errors in Deno web frameworks like Fresh and Oak, covering execution order, async handling, and context passing.

Deno Middleware Errors

Whether you're using Oak, Fresh, or Hono in Deno, middleware errors typically come from incorrect execution order, missing await next(), or context type mismatches.

Missing await next()

The most common mistake — forgetting to call or await the next middleware:

// Oak example
// BAD — downstream middleware never runs
app.use((ctx) => {
  console.log('Request received');
  // Forgot next()!
});

// GOOD
app.use(async (ctx, next) => {
  console.log('Request received');
  await next();
});

Error Handling Middleware

Place the error handler first so it catches errors from all downstream middleware:

// Must be registered FIRST
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.response.status = err.status || 500;
    ctx.response.body = { error: err.message };
    // Report to Bugsly
    await reportError(err, ctx.request);
  }
});

// Other middleware after
app.use(authMiddleware);
app.use(router.routes());

Fresh Middleware (Deno's Official Framework)

Fresh uses file-based middleware in _middleware.ts:

// routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";

export async function handler(req: Request, ctx: FreshContext) {
  // Before the route handler
  const start = Date.now();

  const resp = await ctx.next();

  // After the route handler
  const duration = Date.now() - start;
  resp.headers.set("X-Response-Time", `${duration}ms`);
  return resp;
}

Make sure ctx.next() is always called and awaited — if you conditionally skip it, unmatched routes will hang.

Bugsly captures unhandled exceptions from Deno middleware with the full request context, including headers and route information.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free