Next-auth: how to getSession() to return full user object

Created on 3 Aug 2020  路  2Comments  路  Source: nextauthjs/next-auth

Your question
When i use getSession() the user part only has email, name, image. Is there a way to also get id too?

What are you trying to do
I have created the users table as per your schema and i have also created a UserDetails table to store additional information about user, things like bio etc... I have a FK on the user_id on the UD table. But because i only get the email from the session i have to select * from users where email = '' and then select * from userdetails (or i can do it in a join, obvs) if i had the user_id i wouldnt need either the join or two queries.

So, how can i get either the full user object in the session, or just add in the user_id to the session too.

Or am i using this incorrectly?

  • [ ] Found the documentation helpful
  • [ ] Found documentation but was incomplete
  • [ x] Could not find relevant documentation
  • [x ] Found the example project helpful
  • [ ] Did not find the example project helpful
question

Most helpful comment

ok, i did a deeper dive into the documentation and came acrtoss the callbacks option.

callbacks: {
      /**
       * @param  {object} session      Session object
       * @param  {object} user         User object    (if using database sessions)
       *                               JSON Web Token (if not using database sessions)
       * @return {object}              Session that will be returned to the client
       */
      session: async (session, user, _sessionToken) => {
        session.user.id = user.id;
        return Promise.resolve(session);
      },
    },

that will do what i want.

All 2 comments

ok, i did a deeper dive into the documentation and came acrtoss the callbacks option.

callbacks: {
      /**
       * @param  {object} session      Session object
       * @param  {object} user         User object    (if using database sessions)
       *                               JSON Web Token (if not using database sessions)
       * @return {object}              Session that will be returned to the client
       */
      session: async (session, user, _sessionToken) => {
        session.user.id = user.id;
        return Promise.resolve(session);
      },
    },

that will do what i want.

Thanks for following up with an example of how to do it!

We still get asked this a lot as it's not obvious until you get to the callbacks page, if anyone wants to write up a tutorial to show how to do this (and consume it from an API route) that would be 馃敟!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jimmiejackson414 picture jimmiejackson414  路  3Comments

Xetera picture Xetera  路  3Comments

alephart picture alephart  路  3Comments

ryanbahan picture ryanbahan  路  3Comments

bscaspar picture bscaspar  路  3Comments