next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

How can I access the database user ID through the session variable?

Open nthnluu opened this issue 6 years ago • 8 comments

Your question How do I access the database user ID (aka the Postgres PK of the user) through the session variable returned by getSession()?

What are you trying to do I currently have a Hasura backend, which requires me to pass the user ID through the request header for authorization. I can see that the JWT payload (https://next-auth.js.org/configuration/options#jwt) provides the User ID. However, I couldn't figure out how to persist a JWT session, so I'm currently using database sessions, which don't seem to return the user ID on the session object. I am trying to configure an API route that appends the user ID to the x-hasura-user-ID variable on the request header, then through Apollo Client.

Documentation feedback Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

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

nthnluu avatar Jun 29 '20 21:06 nthnluu

This is essentially what I'm trying to figure out as well, as logged in #366

ryanbahan avatar Jun 29 '20 22:06 ryanbahan

@nthnluu did you end up finding a solution?

asibilia avatar Feb 05 '21 02:02 asibilia

I'm stuck on this as well, can't figure out how I'm meant to be accessing / creating user specific data from the front-end without a userId or some other primary key

oscargws avatar Feb 11 '21 12:02 oscargws

You can persist anything in the JWT using the jwt callback, but only things explicitly returned in the session callback will be available to getSession(), useSession().

https://next-auth.js.org/configuration/callbacks#session

We don't return the user id to session by default, as it may result in GDPR issues for some.

balazsorban44 avatar Feb 11 '21 12:02 balazsorban44

What about username? Why aren't you storing and giving back username at least when someone authenticates with Github?

nerdogram avatar Apr 09 '21 23:04 nerdogram

@nerdogram as said, you can put anything in the session.Also for GitHub. Please check the docs for the session and jwt callbacks.

balazsorban44 avatar Apr 10 '21 08:04 balazsorban44

I'm still not following. I want to add the Github username to my database when the sign in happens. Does this event take place within the Prisma Adapter or in the jwt callback?

nerdogram avatar Apr 10 '21 19:04 nerdogram

ah, sorry, looked over the DB part.

cc @ndom91 could you help out with this? 😊

balazsorban44 avatar Apr 10 '21 21:04 balazsorban44