Get user data in request.user using express and typescript

Issue

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.

Solution

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.

Answered By – hideous

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published