Abhishek Vats
Abhishek Vats

Reputation: 121

Property '_id' does not exist on type 'string | JwtPayload'. Property '_id' does not exist on type 'string'

As you can see in the NodeJS code I'm grabbing the user from the token from Postman provided in the URL but I'm struggling to get back the _id property from the given token number. What I want is that id in the decoded._id so that I can use that id in further operations

const jwt = require("jsonwebtoken");
const User = require("../model/users");
const auth = async (req, res, next) => {
  try {
    const token = req.header("Authorization").replace("Bearer", "");
    const decoded = jwt.verify(
      token,
      "thisisfromabhishek"
    )`the property _id does not exist on decoded`;
    const user = await User.findOne({
      _id: decoded._id,
      "tokens.token": token,
    });

    if (!user) {
      throw new Error();
    }
    req.token = token;
    req.user = user;
    next();
  } catch (e) {
    res.status(401).send({ error: "Please authenticate." });
  }
};

module.exports = auth;

Upvotes: 12

Views: 15289

Answers (4)

mohammad barzegar
mohammad barzegar

Reputation: 387

The typescript doesn't know about your types, so you can easily write precise type with this way(It's necessary part of the code:

import jwt, { JwtPayload } from "jsonwebtoken";
import { RequestHandler } from "express";

interface IJwtPayload extends JwtPayload {
  _id: string;
}

const auth: RequestHandler = async (req, res, next) => {
  const decoded = jwt.verify(token, 'JWT_SECRET_KEY') as IJwtPayload;

  req.user = await User.findOne({ _id: decoded._id, 'tokens.token': token })
}

Upvotes: 1

Cedric Karungu
Cedric Karungu

Reputation: 11

Typescript don't know about _id in token, add JwtPayloqd type or interface with id

interface JwtPayload {
    id: string;
}

const decoded = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload;
console.log(decoded);

Upvotes: 1

roman retiunsky
roman retiunsky

Reputation: 351

Typescript don't know about _id in token. Data declaration should help.

interface JwtPayload {
  _id: string
}

const { _id } = jwt.verify(token, 'thisisfromabhishek') as JwtPayload

req.user = await User.findOne({ _id, 'tokens.token': token })

Upvotes: 35

Asim Imam
Asim Imam

Reputation: 373

you have not given space after Bearer.

const token = req.header('Authorization').replace('Bearer', '') //here is the problem place space after Bearer
          const decoded = jwt.verify(token, 'thisisfromabhishek')

Upvotes: 0

Related Questions