app.ts:
app.use(passport.authenticate("jwt", { session: false }));
// -------------------protected routes
//this home router returns the authenticated employee info
app.get("/home", (request: Request, response: Response) => {
response.json({ message: request.user });
});
// app.use("/employee", passport.authenticate("jwt", { session: false }));
app.use("/employee", employeeRouter);
// ------------ error handling. It only has 500 error, but later more errors will be handled.
app.use(function (err: Error, req: Request, res: Response, next: NextFunction) {
res.status(500).send({ error: "internal server error" });
console.error(err.stack);
next();
});
This is the code I have. at the first line, I set the jwt authentication as a global middleware, intending to set that any routers coming after this should be protected. The router app. get("/home") can successfully access the authenticated user, and be able to send it as a response. However, the routers in the "employeeRouter" do not have access to the user and return undefined. employeeRouter.ts
employeeRouter.get(
"/profile",
(request: Request, res: Response, next: NextFunction) => {
response.json({ message: request.user });
}
);
For example, this router is not in the app.ts file, and it is not able to access request.user.
Could anyone tell me how to fix it so that all of the files can access to the authenticated user?