How to use passportjs in Nextjs Server Side (getServerSideProps)?

Viewed 104

I want to get the user session from server side (getServerSideProps). Right now I'm using the passportjs middleware pattern and then getting the user object on the API side. Is there a function or method in passport which allows me to do this?

1 Answers

Using the official example:

https://github.com/vercel/next.js/tree/canary/examples/with-passport

You can use this in your page to get logged in user data from server side:

import { getLoginSession } from '../lib/auth'
import { findUser } from '../lib/user'

// ...

export async function getServerSideProps({req}) {

  const session = await getLoginSession(req)
  const user = (session && (await findUser(session))) ?? null

  console.log(user)

  return {
    props: {
      user,
    }
  }
}

Related