0

I am using Next.js and have successfully added passport.js, thus getting a user back after a successful login. \0/

However what I want is the req.user to be available to my api/user route...

In this example repo in middleware/auth.js

It mentions in a use.() function below...

Initialize mocked database Remove this after you add your own database

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) => {
 // 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

This is my api/user route:

import nextConnect from 'next-connect'
import auth from '../../middleware/auth'

const handler = nextConnect()

handler
  .use(auth)
  .get((req, res) => {
    // You do not generally want to return the whole user object
    // because it may contain sensitive field such as !!password!! Only return what needed

    // const { _id } = req.user
    // res.json({ user: { _id } })
    console.log("in api/user req.user ", req.user); // returns undefined.

    if (req.user) {
      const { _id } = req.user
      res.json({ user: { _id } })
    } else {
      res.json({ user: null })
    }
  })


export default handler;

My rational is the repo also has a hook which calls the /api/user route to see if the req.user exists...

import useSWR from 'swr'

export const fetcher = (url) => fetch(url).then((r) => r.json())

export function useUser() {
  const { data, mutate } = useSWR('/api/user', fetcher)
  // if data is not defined, the query has not completed

  console.log("data in useUser hooks!", data);

  console.log("data?.user ", data?.user);
  const loading = !data
  const user = data?.user
  return [user, { mutate, loading }]
}

By the contents of the repo it would appear you should be able to get req.user , from setting up the database in the middleware/auth file and how would you do this and thus get it in the api/user route?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141

1 Answers1

0

Instead of using req.user use req.session and then console.log this

Fahad Ali
  • 47
  • 1
  • 7