Express: Why is the last middleware always being called?

I’m making my first MERN app and I’m encountering an issue with my middleware. The last middleware catchError is always being called, and it’s returning a 500 Internal Server Error response (which I defined) with the error message “User not found”. I can’t figure out why this is happening. Here’s a short version of the server.ts file:

mongoose
  .connect(URI)
  .then(() => console.log("Connected to Database"))
  .catch((err) => console.log(err));

app.use(express.json({ limit: "4mb" }));
app.use(cors({ origin: "http://localhost:5173", credentials: true }));
app.use(cookieParser(SECRET));
app.use(
  session({
    secret: SECRET,
    saveUninitialized: false,
    resave: false,
    store: MongoStore.create({ client: mongoose.connection.getClient() }),
    cookie: {
      sameSite: false,
      secure: false,
      maxAge: 1000 * 60 * 60 * 24,
      httpOnly: true,
    },
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(blogsRouter);
app.use(usersRouter);

app.use(catchError); // Error middleware is the last one
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

And here’s my users.ts routes file:

const router = Router();

router.get(
  "/users/:id",
  checkForAuthentication,
  async (req: Request, res: Response) => {
    const userId: string = req.params.id;
    try {
      const objectId = new Types.ObjectId(userId);
      const user = await User.findById(objectId);
      if (user) return res.send({ user });
      return res
        .status(404)
        .send({ error: `User with ID ${userId} not found` });
    } catch (err) {
      return res.status(400).send({ error: "Invalid ID" });
    }
  }
);

router.post(
  "/users/sign-up",
  validateBody(userSchema),
  async (req: Request, res: Response) => {
    const u: UserType = req.body;
    const existingUser = await User.findOne({ username: u.username });
    if (existingUser) {
      return res.status(400).send({ user: u, error: "Username taken" });
    }

    const hashedPass = await hashPassword(u.password);
    const newUser = new User({ username: u.username, password: hashedPass });

    try {
      const savedUser = await newUser.save();
      req.login(savedUser as any, (err: Error) => {
        if (err) {
          return res.status(500).send({ error: err.message });
        }
        return res.status(201).send({ username: savedUser.username });
      });
    } catch (err) {
      if (err instanceof Error) {
        return res.status(400).send({ user: newUser, error: err.message });
      }
      return res.status(400).send({ user: newUser, error: err });
    }
  }
);

router.post(
  "/users/sign-in",
  (req: Request, res: Response, next: NextFunction) => {
    passport.authenticate("local", function (err: any, user: any) {
      if (err) {
        return res.status(400).send({ error: err });
      }
      if (!user) {
        return res.status(401).send({ error: "User login error" });
      }
      req.logIn(user, function (secondErr) {
        if (secondErr) {
          return res.status(500).send({ error: "Login failed" });
        }
        return next();
      });
    })(req, res, next);
  },
  (req: Request, res: Response) => {
    const u = req.user;
    req.isAuthenticated();
    if (u) {
      return res.send({
        username: u.username,
        msg: "Successful login",
      });
    }
  }
);

router.post(
  "/users/sign-in/status",
  checkForAuthentication,
  (req: Request, res: Response) => {
    return res.send({ user: req.user, msg: "Client authenticated" });
  }
);

router.post("/users/log-out", (req: Request, res: Response) => {
  if (!req.user) return res.status(401).send({ error: "Already logged out" });
  req.logout((err) => {
    if (err) return res.status(500).send({ error: "Logout failed" });
    res.send({ msg: "Logout successful" });
  });
});

router.patch(
  "/users/:id/change-password",
  checkForAuthentication,
  async (req: Request, res: Response) => {
    const userId: string = req.params.id;
    const oldPassword: string = req.body.oldPassword;
    const newPassword: string = req.body.newPassword;

    try {
      const objectId = new Types.ObjectId(userId);
      const hashedNewPassword = await hashPassword(newPassword);

      const user = await User.findById(objectId);
      if (!user)
        return res.status(404).send({ error: "User not found weeweewee" });
      if (!(await comparePassword(oldPassword, user.password))) {
        return res.status(400).send({ error: "Old password doesn't match" });
      }

      user.password = hashedNewPassword;
      user.save();
      res.status(200).send({ msg: "Password updated successfully" });
    } catch (err) {
      console.error(err);
      return res.status(400).send({ error: "Invalid ID or other error" });
    }
  }
);

export default router;

I changed all of the error messages I wrote in my routes so I could see if they were coming from any of them, but it seems like the error is coming from elsewhere. Why is this happening? Thanks in advance!

The source code: https://github.com/vempr/rt-chat/tree/main/server

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật