Next-auth: Overwrite user object in session

Created on 24 Nov 2020  路  2Comments  路  Source: nextauthjs/next-auth

Your question
There is a way to overwrite the existing user object in session?

What are you trying to do
I'm creating a multitenant application and I need to store the TenantID in the session but I'm unable to add another property besides name, email and picture

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

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

Most helpful comment

@jjzcru This is how I'm doing it using a custom provider:

const options = {
  site: BASE_URL,
  providers: [
    {
      ...
      profile: (profile: Record<string, string>) => {
        return { ...profile, id: profile.sub };
      },
    }
  ],
  callbacks: {
    session: async (
      session: SessionBase,
      user: Record<string, string>,
    ): Promise<GenericObject> => {
      user.id = user.sub;
      session.user = user;
      return Promise.resolve(session);
    },
    jwt: async (
      token: GenericObject,
      user: User,
      account: GenericObject,
      profile: GenericObject,
    ): Promise<GenericObject> => {
      return Promise.resolve(profile ? profile : token);
    },
  },
};

Ignore the types if you're not using typescript.

In this example, I'm adding the attribute id to the user. You can add attributes to the session in the session callback.

All 2 comments

@jjzcru This is how I'm doing it using a custom provider:

const options = {
  site: BASE_URL,
  providers: [
    {
      ...
      profile: (profile: Record<string, string>) => {
        return { ...profile, id: profile.sub };
      },
    }
  ],
  callbacks: {
    session: async (
      session: SessionBase,
      user: Record<string, string>,
    ): Promise<GenericObject> => {
      user.id = user.sub;
      session.user = user;
      return Promise.resolve(session);
    },
    jwt: async (
      token: GenericObject,
      user: User,
      account: GenericObject,
      profile: GenericObject,
    ): Promise<GenericObject> => {
      return Promise.resolve(profile ? profile : token);
    },
  },
};

Ignore the types if you're not using typescript.

In this example, I'm adding the attribute id to the user. You can add attributes to the session in the session callback.

Since no response from the issue author, I am assuming @jachinte's comment helped. If not, please feel free to reopen/comment.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

simonbbyrne picture simonbbyrne  路  3Comments

loonskai picture loonskai  路  3Comments

iaincollins picture iaincollins  路  3Comments

SharadKumar picture SharadKumar  路  3Comments

benoror picture benoror  路  3Comments