I’m trying to create a middleware to ensure the user is admin, but when I print request.customer, the result is undefined.
This is what I’m doing:
import { NextFunction, Request, Response } from "express";
import { prisma } from "../../prisma";
export async function ensureAdmin(
request: Request,
response: Response,
next: NextFunction
) {
const { id } = request.customer;
const customer = await prisma.customer.findUnique({
where: {
id,
},
});
console.log(request.customer);
return next();
}
request.customer returns this: Property 'customer' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'
So I declared the express namespace by adding the customer id, like this:
declare namespace Express {
export interface Request {
customer: {
id: string;
}
}
}
I have no errors but at the same time when I print request.customer it comes undefined.
Advertisement
Answer
I think you need to correctly implement the middleware as it is described in this documentation: Using middleware.
There you will have the (req, res, next) function. The req is of type Request and contains parameters for query parameters (called via req.params), headers (called via req.headers['...']) and many more. Wherever your customer id is encoded, you need to extract it from your request.