I'm trying to create a middleware in Deno using oak, I want to validate a jwt token and then if everything is OK add the payload to the request body.
Found this code:
import { validateJwt } from "https://deno.land/x/djwt/validate.ts"
import { key } from "../utils/jwt.js";
export const validate = async ({request, cookies}, next) => {
const token = await cookies.get("token");
const result = await validateJwt(token, key, { isThrowing: false });
if(result) {
request.auth = true;
request.username = result.payload.username;
}
await next();
}
but is not working any more and haven't been able to find anything about how to add properties to the request.
What I want to achieve at the end is to access the payload inside the controller.
Thanks in advance. Any guidance will be much appreciated
Took a while but found how to do it. To pass a variable from a middleware to the route or another middleware you don't use the Request anymore but instead you use the context State
app.use(async (ctx, next) => {
// do whatever checks to determine the user ID
ctx.state.userId = userId;
await next();
delete ctx.state.userId; // cleanup
});
app.use(async (ctx, next) => {
// now the state.userId will be set for the rest of the middleware
ctx.state.userId;
await next();
});