When using Passport with Express, Typescript thinks req.user is possibly undefined inside a route when using an auth middleware. When using an auth middleware, I'd like req.user to be defined in all cases because otherwise, the middleware will return 401 unauthorized response.
If the route is using an auth middleware like this:
app.use( '/users', passport.authenticate('bearer', { session: false }), usersRouter );
The routes within /users shouldn't have the user being possibly undefined since it never will be.
How does one achieve this, without declaring a custom request interface to use for each route?
In short, you cannot make Typescript understand whether your middleware set req.user or not as TS doesn't "understands" how middlewares work in Express. However, you can extend the request interface and use your custom implementation where you know the value is set (aka in the authenticated routes).
Defining the custom interface:
import { Request } from 'express';
import { YourUserDefinitionInterface } from './your-user-definition.interface.ts';
export interface AuthenticatedRequest extends Request {
user: YourUserDefinitionInterface
}
Using it in a route:
// The below route is behind the auth middleware
app.get('/some-path', (req: AuthenticatedRequest) => {
// Your handling logic here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With