I find myself constantly having to include code like
if (!req.user) return res.status(401).send()
The first solution that comes to mind is creating an express middleware for this. However, even though I can prevent non-logged in users from accessing the route, I am struggling to properly type the express req.
When I try to override the "req" parameter, the router raises errors because the user key in "Express.User" is considered optional.
I don't think modifying the global override so that "user" is required is a good idea since it should only be required after passing through the middleware validation. How can I solve this issue?
Here's a snippet of relevant code to provide more context.
Global Express Override
declare global {
namespace Express {
interface User extends TUser {
_id: ObjectId
}
}
}
Desired Outcome
// Router
router.post('/', sessionMiddleware, controller)
// Middleware
const sessionMiddleware = (req: Request, res: Response, next: NextFunction) => {
if (!req.user) return res.status(401).send()
next()
}
// Controller
const controller = (req: RequestWithRequiredUser, res: Response) => {
// user here can't possibly be typed undefined
const user = req.user
...
}
Current Workaround:
const controller = (req: Request, res: Response) => {
if (!req.user) return res.status(401).send()
...doSomethingElse
}