title: Next.js and Mongoose and Passport.js: req.user is undefined
body: <p>I am using the relatively newer setup with Next.js API routes, this doesn't use express but instead the <a href="https://nextjs.org/docs/api-routes/introduction" rel="nofollow noreferrer">API setup</a> to create your routes to an endpoint.</p>
  <p>My problem is I'd like to have a route called <code>api/user</code> which will return the user i.e. <code>req.user</code>:</p>
  <p>The following comes from <a href="https://github.com/vercel/next.js/blob/canary/examples/with-passport-and-next-connect/middleware/auth.js" rel="nofollow noreferrer">with-passport-and-next-connect</a></p>
  <pre><code>import nextConnect from 'next-connect'
  import auth from '../../middleware/auth'
  
  const handler = nextConnect()
  
  handler
    .use(auth)
    .get((req, res) =&gt; {
  
      if (req.session.user) {
        const { _id } = req.session.user
        res.json({ user: { _id } })
      } else {
        res.json({ user: null })
      }
  
    })
  
  export default handler
  </code></pre>
  <p>That file references this <a href="https://github.com/vercel/next.js/blob/canary/examples/with-passport-and-next-connect/middleware/auth.js" rel="nofollow noreferrer">auth</a> file:</p>
  <pre><code>import nextConnect from 'next-connect'
  import passport from '../lib/passport'
  import session from '../lib/session'
  
  const auth = nextConnect()
    .use(
      session({
        name: 'sess',
        secret: process.env.TOKEN_SECRET,
        cookie: {
          maxAge: 60 * 60 * 8, // 8 hours,
          httpOnly: true,
          secure: process.env.NODE_ENV === 'production',
          path: '/',
          sameSite: 'lax',
        },
      })
    )
    .use((req, res, next) =&gt; {
      // Initialize mocked database
      // Remove this after you add your own database
      req.session.users = req.session.users || []
      next()
    })
    .use(passport.initialize())
    .use(passport.session())
  
  export default auth
   
  </code></pre>
  <p>I have added this in my version:</p>
  <pre><code>  .use((req, res, next) =&gt; {
      connectDB()
      next()
    })
  </code></pre>
  <p>But that yields nothing.</p>
  <p>In <code>api/login</code> I added this line</p>
  <pre><code>req.session.user = req.user;
  </code></pre>
  <p>after the authenticate function. But that doesn’t add the user to the session object.</p>
  <pre><code>   handler
    .use(auth)
    .post((req, res, next) =&gt; {
      emailValidator(req, res, next, 'email', 'password');
    },
      async (req, res, next) =&gt; {
        await connectDB();
  
        passport.authenticate('local', (err, user, info) =&gt; {
  
          req.session.user = req.user;
  </code></pre>
  <p>Could anyone please help me with this?</p>
  <p>Thanks in advance.</p>