Accessing user data inside withPageAuthRequired

I am building a web app where on authentication the user is taken to a protected route, then user specific data is queried from a DB and displayed.

I am using withPageAuthRequired to secure the page. I want to access the user’s data inside the getServerSideProps function so that I can query relevant data.

My code

export const getServerSideProps = withPageAuthRequired({

  async getServerSideProps(context) {

    //Querying data from DB
    // I want to be able to access the user's info here
    const { db } = await connectToDatabase()
    const data = await db.collection("users").find({}).project({ first_name: 1 }).toArray()

    return {
      props: { properties: data},
    }
  }

});

SDK: nextjs-auth0 v1.4.0
Node v16.0
NextJS v10.0

Previous message deleted due to SPAM reasons.

I have figure out how to get the user’s data in the new nextjs sdk

You need to import getSession and pass that the context request, and it will return a user object.

// import getSession to access user data on the server
import { withPageAuthRequired, getSession } from '@auth0/nextjs-auth0'

export const getServerSideProps = withPageAuthRequired({

  async getServerSideProps(context) {

    // Getting user data from Auth0
    const user = getSession(context.req).user
    //returns an object like this one: {name: 'Bob', email: 'bob@email.com', email_verified: true}

    //Querying data from DB
    const { db } = await connectToDatabase()
    const data = await db.collection("users").find({email: user.email}).project({ first_name: 1 }).toArray()

    return {
      props: { properties: data},
    }
  }

});

1 Like

Glad to hear that and thanks for sharing it with the rest of community!