DEV Community

Emmanuel Kelechi Igwesi
Emmanuel Kelechi Igwesi

Posted on

Property 'id' does not exist on type 'string | JwtPayload' [duplicate]

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;
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
moscode profile image
Moscode

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

const verified = jwt.verify(token, configs.JWT_SECRET)
Enter fullscreen mode Exit fullscreen mode

became

const verified = jwt.verify(token, configs.JWT_SECRET) as JwtPayload
Enter fullscreen mode Exit fullscreen mode

With Bug

Image description

Fixed bug

Image description

Collapse
 
dchief profile image
Emmanuel Kelechi Igwesi

I added id: string; to the jwtpayload but still got same error, code shown below:

export interface JwtPayload {
    [key: string]: any;
    id: string;
    iss?: string | undefined;
    sub?: string | undefined;
    aud?: string | string[] | undefined;
    exp?: number | undefined;
    nbf?: number | undefined;
    iat?: number | undefined;
    jti?: string | undefined;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mafelo profile image
Kennedy Mafelo
import jwt, { type JwtPayload, type Secret } from "jsonwebtoken";

interface CustomJwtPayload extends JwtPayload {
    _id: string;
}

 const decoded = jwt.verify(
        token,
        process.env.JWT_SECRET as Secret
    ) as CustomJwtPayload;
Enter fullscreen mode Exit fullscreen mode