D
Deno

help

Help, does the middleware example in the Deno Fresh documentation not work for anyone else?

EEGamalielGZ10/3/2023
I tried to follow the example in Deno Fresh about middlewares, but it doesn't work, the content ctx.state.data doesn't appears to be undefined whatever I do
DAHDeno AI Helper10/3/2023
I'm sorry to hear that you're having trouble with the middleware example in the Fresh documentation. Let's try to debug this issue together. 🦕 First, let's make sure that you're correctly setting the ctx.state.data in your middleware. Here's the example from the documentation:
// routes/_middleware.ts

export const handler = [
timing,
logging,
];

async function timing(
_req: Request,
ctx: MiddlewareHandlerContext,
): Promise<Response> {
const start = performance.now();
const res = await ctx.next();
const end = performance.now();
const dur = (end - start).toFixed(1);
res.headers.set("Server-Timing", `handler;dur=${dur}`);
return res;
}

async function logging(
req: Request,
ctx: MiddlewareHandlerContext,
): Promise<Response> {
const res = await ctx.next();
console.log(`${req.method} ${req.url} ${res.status}`);
return res;
}
// routes/_middleware.ts

export const handler = [
timing,
logging,
];

async function timing(
_req: Request,
ctx: MiddlewareHandlerContext,
): Promise<Response> {
const start = performance.now();
const res = await ctx.next();
const end = performance.now();
const dur = (end - start).toFixed(1);
res.headers.set("Server-Timing", `handler;dur=${dur}`);
return res;
}

async function logging(
req: Request,
ctx: MiddlewareHandlerContext,
): Promise<Response> {
const res = await ctx.next();
console.log(`${req.method} ${req.url} ${res.status}`);
return res;
}
In this example, ctx.state.data is not being set. If you want to set ctx.state.data, you would need to do so in one of your middleware functions. For example:
async function setData(
_req: Request,
ctx: MiddlewareHandlerContext,
): Promise<Response> {
ctx.state.data = "Some data";
return await ctx.next();
}
async function setData(
_req: Request,
ctx: MiddlewareHandlerContext,
): Promise<Response> {
ctx.state.data = "Some data";
return await ctx.next();
}
And then include setData in your handler array:
export const handler = [
setData,
timing,
logging,
];
export const handler = [
setData,
timing,
logging,
];
If you've done this and ctx.state.data is still undefined, there might be an issue with the order of your middleware functions. The ctx.next() function will call the next middleware in the handler array, so if you're trying to access ctx.state.data in a middleware function that comes before setData in the handler array, ctx.state.data will be undefined. If none of these suggestions solve your issue, could you please provide more details about

Looking for more? Join the community!