I just want to get user by id but I got an error that states id does not exist on type string , my code is shown below:
import asyncHandler from "express-async-handler";
import { NextFunction, Request, Response } from "express";
import User from "../models/User";
import jwt from "jsonwebtoken";
import configs from "../config/config";
const protect = asyncHandler (async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.cookies.token
if (!token) {
res.status(401)
throw new Error("Not authorized, please login");
}
// Verify Token
const verified = jwt.verify(token, configs.JWT_SECRET)
// Get user id from token
const user = await User.findById(verified.id).select("-password")
if (!user) {
res.status(401)
throw new Error("User was not found")
}
req.user = user
next()
} catch (error) {
}
});
export default protect;
Top comments (3)
I had this same issue about a few minutes ago.
The error occurs because the type of the "verified" variable is not specified; Hence it is 'string | JwtPayload'.
So I solved the error by specifying the type to be "JwtPayload". I.e
became
With Bug
Fixed bug
I added id: string; to the jwtpayload but still got same error, code shown below: