2

I'm rewriting the backend of an ExpressJS application into Typescript. In auth.routes.ts, I encountered an error related to middleware(authMiddleware). As I understand it, there is a typing error, because the same file in the js extension works fine.

Please help me figure this out.

Below is the corresponding code


auth.routes.ts

import { Router } from "express"
import authMiddleware from "../middleware/auth.middleware"
import authController from "../controllers/authController"

const router = Router()

router.get("/", authMiddleware, authController.auth)

export default router

auth.middleware.ts


import "dotenv/config"
import { NextFunction, Response } from "express"
import jwt, { JwtPayload, Secret } from "jsonwebtoken"
import { CustomHeaders } from "../models"

const secretKey: Secret = process.env.secretKey as Secret

interface AuthRequest extends Request {
  user?: JwtPayload
}

function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
  if (req.method === "OPTIONS") {
    next()
  }

  try {
    const token = (req.headers as CustomHeaders).authorization?.split(" ")[1]

    if (!token) {
      return res.status(401).json({ message: "Unauthorized" })
    }
    const decoded: JwtPayload = jwt.verify(token!, secretKey) as JwtPayload
    req.user = decoded

    next()
  } catch (error) {
    return res.status(400).json({ message: "Bad Request" })
  }
}

export default authMiddleware


Error description:

No overload matches this call. The last overload gave the following error. Argument of type '(req: AuthRequest, res: Response<any, Record<string, any>>, next: NextFunction) => Response<any, Record<string, any>> | undefined' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Type '(req: AuthRequest, res: Response<any, Record<string, any>>, next: NextFunction) => Response<any, Record<string, any>> | undefined' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Types of parameters 'req' and 'req' are incompatible. Type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' is missing the following properties from type 'AuthRequest': cache, credentials, destination, integrity, and 13 more.ts(2769)

I tried to ask chatGPT about my problem, but I also received non-working variationss

2 Answers 2

0

this solved my problem

declare global {
  namespace Express {
    interface Request {
      email: string
      password: string
      user?: JwtPayload
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

The reason you're getting this error is because middlewares are expected to return void. But you're returning return res.status(401).json({ message: "Unauthorized" }) & return res.status(400).json({ message: "Bad Request" }) inside the function.

You could try it like below.

res.status(401).json({ message: "Unauthorized" });
return;
res.status(400).json({ message: "Bad Request" });
return;

Also, for good measures, mention the return type of your function like so

function authMiddleware(req: AuthRequest, res: Response, next: NextFunction): void {
    // rest of your code
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.