Please refer to the documentation, the example project and existing issues before creating a new issue.
Your question
A clear and concise question.
I'm using email/password auth and have successfully set up my database. I'm wondering the best way to retrieve my user ID, since the session's user object only contains name/email/password.
What are you trying to do
A description of what you are trying to do.
Have access to the ID of the user in my database, so I can use that as a primary key elsewhere instead of their email.
Documentation feedback
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.
I think that implementing a custom callback might be the answer, but am still unclear on how exactly to implement custom callbacks and where this would go.
I'm facing the same question. I had a look into the code and found this: https://github.com/iaincollins/next-auth/blob/main/src/server/routes/session.js#L69-L79
I think it makes sense to explicitly limit the fields that are exposed. However, I'm not sure if the userId should not be in there.
I'm happy to provide a PR if this change is welcome :)
Hi there, the best way to do this right now depends on how session support is configured.
If JSON Web Tokens are enabled use the session() callback to pass data from the JWT to the session object that is returned to the client.
If using database sessions then you can use the accessKey returned in the session to look up the User ID in the session table. This avoids exposing the User ID to the front end, while providing a unique identifier.
There are no tutorials for this yet, by standard SQL or MongoDB queries apply and can be used in the session() callback to add data to the session response returned to the client.
@iaincollins thanks for your quick response! I went with JWTs and expose the user-id as you described:
const options = {
site: process.env.SITE || 'http://localhost:3000',
providers: [
Providers.Email({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD
}
},
from: process.env.EMAIL_FROM
}),
],
session: {
jwt: true,
},
database: process.env.DB_CONNECTION_STRING + '?entityPrefix=nextauth_',
callbacks: {
async session(session, token) {
// expose user id
return Promise.resolve({ ...session, user: { ...session.user, id: token.user.id } })
}
}
}
@iaincollins @timoweiss Thanks for explaining this further and sharing that code snippet! This was super helpful.
Most helpful comment
@iaincollins thanks for your quick response! I went with JWTs and expose the user-id as you described: