I getting annoyed about typescript in my node api. I have written a auth.ts At first typescript has not accepted the req.user.
// error messages
01:01:07 ⨯ Unable to compile TypeScript:
middleware/auth.ts(34,9): error TS2339: Property ‘user’ does not exist on type ‘Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>’.
enter image description here
// @types/custom.d.ts
import { Request } from "express";
import { IUser } from "../models/user.model";
declare global {
namespace Express {
interface Request{
user?: IUser;
}
}
}
// middleware/auth.ts
import { NextFunction, Request, Response } from "express";
import { CatchAsyncError } from "./catchAsyncError";
import ErrorHandler from "../utils/ErrorHandler";
import jwt, { JwtPayload } from "jsonwebtoken";
import { redis } from "../utils/redis";
// authenticated User
export const isAutheticated = CatchAsyncError(
async (req: Request, res: Response, next: NextFunction) => {
const access_token = req.cookies.access_token;
console.log(access_token);
if (!access_token) {
return next(
new ErrorHandler("Please login to access this resources", 400)
);
}
const decodeed = jwt.verify(
access_token,
process.env.ACCESS_TOKEN as string
) as JwtPayload;
if (!decodeed) {
return next(new ErrorHandler("Access token is not valid ", 400));
}
const user = await redis.get(decodeed.id);
if (!user) {
return next(new ErrorHandler("User not found", 400));
}
req.user = JSON.parse(user) ;
next();
}
);
```