title: typescript: req.user is possibly 'undefined' - express and passport js
body: <p>I have a Nodejs typescript authentication system that works using passport.</p>
  <p>My problem is that when I use <code>req.user</code> in a route I get this error on <code>req.user</code>: <code>Object is possibly 'undefined'.</code></p>
  <p>This is a normal behavior of Typescript but I am using a middleware to protect routes that I want to use <code>req.user</code> in them and this way <code>req.user</code> cannot be undefined.</p>
  <p><strong>This is where I extend <code>Express.User</code> Type:</strong></p>
  <pre><code>import { users } from &quot;@prisma/client&quot;;
  
  declare global {
      namespace Express {
          interface User extends users {}
      }
  }
  </code></pre>
  <p><strong>This is the middleware that I'm using to protect routes for logged in users:</strong></p>
  <pre><code>export function checkIsAuthenticated(req: Request, res: Response, next: NextFunction) {
      if (req.isAuthenticated()) {
          if (!req.user) req.logOut();
          else return next();
      }
      res.status(400).json({
          errors: [{ message: &quot;no user logged in&quot; }],
      });
  }
  </code></pre>
  <p><strong>And this is the route for getting the user info:</strong></p>
  <pre><code>export function userRoute(req: Request, res: Response) { // defining the route
      res.json({
          id: req.user.id,               // I'm getting the error in these 4 lines
          username: req.user.username,   //
          email: req.user.email,         //
          role: req.user.role,           //
      });
  }
  
  router.get(&quot;/user&quot;, checkIsAuthenticated, userRoute); // using the route
  </code></pre>
  <p>I don't want to check if user is defined because I don't want to do it in every route and that's not a good practice. That's why middleware are for.</p>
  <p>I'm not good at Typescript so I need some help to fix it. <strong>Thanks</strong></p>