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

Discord user ID in getServerSession data

Open vunsh opened this issue 3 years ago • 1 comments

Description 📓

I'm currently working with NextJS v13, and I'm running into an setback with the Discord provider. Here is the current data returned with getServerSession:

{
  user: {
    name: 'vunsh',
    email: undefined,
    image: 'https://cdn.discordapp.com/avatars/640345794108719110/aef7a749881a267f30303a4ad5d86e9f.png'
  }
}

As you can see, there is no "id" associated with this. This makes it hard to authenticate routes on the server side as I can't compare ids to what I have in my database. I'm unsure if the client side method "useSession" provides the full data, but either way it should be provided here.

When looking at the data in the source code, it seems there is an id field. I'm unsure as to why I'm unable to access it here.

For reference, here is my code just in case I'm doing something wrong

import { getServerSession } from "next-auth/next"

import { authOptions } from "@/lib/auth"

export async function getCurrentUser() {
  const session = await getServerSession(authOptions)


  return session
}

If you are experiencing something similar, I made this simple workaround that gets the id from the avatar link. This is less than ideal though:

import { getServerSession } from "next-auth/next"

import { authOptions } from "@/lib/auth"

export async function getCurrentUser() {
  const session = await getServerSession(authOptions)

  const id = session?.user?.image?.split('/')[4]?.split('.')[0]
  session.user.id = id

  return session
}

If I made a silly mistake somewhere, please correct me. I'm very new to nextauth so it's definitely possible, but I wasn't able to find any information so here I am <3

How to reproduce ☕️

You can reproduce this by creating a nextjs project with nextauth and using Discord as a provider. Above you can see my code for getting the data serverside, here's my authOptions just in case:

import DiscordProvider from 'next-auth/providers/discord'

const scopes = ['identify']
export const authOptions = {
        providers: [
          DiscordProvider({
              clientId: process.env.DISCORD_CLIENT_ID,
              clientSecret: process.env.DISCORD_CLIENT_SECRET,
              authorization: {params: {scope: scopes.join(' ')}},
          })
        ],
}

Also scopes is not the issue here, using the default nextauth Discord scope also doesn't give me an ID, though it does give me an email.

Contributing 🙌🏽

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

vunsh avatar Aug 07 '23 03:08 vunsh

check out the session and jwt callbacks https://next-auth.js.org/configuration/callbacks

balazsorban44 avatar Aug 08 '23 09:08 balazsorban44