nextauthjs / nextauthjs/next-auth

Add ability to extend database session and use in session callback

Open
#7,150 3 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement triage
Dominant language
TypeScript
Stars
28.4k
Forks
4k
PR merge metrics
No merged PRs in 30d

Description

Description 📓

Currently, as you can see here, only a subset of the session (from the database) is passed to the session callback.

Pasting here as well:

// packages/core/src/lib/routes/session.ts
const sessionPayload = await callbacks.session({
        // By default, only exposes a limited subset of information to the client
        // as needed for presentation purposes (e.g. "you are logged in as...").
        session: {
          user: {
            name: user.name,
            email: user.email,
            image: user.image,
          },
          expires: session.expires.toISOString(),
        },
        user,
      })

If I want to extend that session to add additional properties and use them within the session callback, I need to go back to the database with the sessionToken (which is not available within the session call so I end up needing to do a custom initializer to pass it in). It's not very efficient to do the extra database query, and the DX is a pain.

I would love to have the ability to extend which session fields we pass (maybe using a whitelist?), or better yet, we could just pass the session to the callback directly how we get it from the DB, and omit any unnecessary fields (like id for example).

How to reproduce ☕️

N/A

Contributing 🙌🏽

Yes, I am willing to help implement this feature in a PR

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with packages/core/src/lib/routes/session.ts, especially the database-session path and the callbacks.session call shown in the issue. Trace which session fields come from the database and define how the callback should receive additional fields while omitting unnecessary ones; done means the callback can use extended session data without an extra database query.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
authentication, backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.