Search code examples
node.jstypescriptapijwtmiddleware

Error creating verifyTokenAdmin middleware


I'm trying to create two middlewares, an authentication middleware and a middleware that checks if the user in question has "isAdmin" true inside its database. The authentication middleware works perfectly, but to make the admin middleware work, I tried to put req.users = data; inside, but it returns me the error:

Property 'users' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)

auth middleware:

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

interface TokenPayload {
  id: string;
  iat: number;
  exp: number;
}

export default async function authMiddleware(
  req: Request, res: Response, next: NextFunction
  ) {
    const { authorization }  = req.headers;

    if (!authorization) {
      return res.status(401).json('Invalid Authorization');
    };

    const token = authorization.replace('Bearer', ' ').trim();

    try {
      const secret = process.env.JWT_SECRET as string;
      const data = jwt.verify(token, secret);

      req.users = data;

      const { id } = data as TokenPayload;

      req.userId = id;

      return next();
    } catch (err) {
      return res.status(401).json(err);
    }
}

In auth middleware admin, in users it returns the same error

Property 'users' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)

auth middleware admin

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import authMiddleware from './AuthMiddlewares';

  
export default async function authAdminMiddleware(
    req: Request, res: Response, next: NextFunction,
) {
    authMiddleware(req, res, () => {
        if (req.users.isAdmin) {
            next();
        } else {
            res.status(403).json("You are not alowed to do that!");
        }
    })
}


Solution

  • You can use declaration merging to declare the additional property users in your req object:

    declare global {
      namespace Express {
        interface Request {
          users: any
        }
      }
    }
    

    (See also here.)