Getting id of user with next-auth

I'm trying to set up next-auth with discord, but I can't get the user ID and discriminator. [..nextauth].ts
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET
})
],
callbacks: {

session: async ({ session, user }) => {
console.log("SESSION", session)
console.log("USER", user)


return {
...session,
user: user,
};
},
}
});
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET
})
],
callbacks: {

session: async ({ session, user }) => {
console.log("SESSION", session)
console.log("USER", user)


return {
...session,
user: user,
};
},
}
});
This is what it prints out.
SESSION {
user: {
name: 'Børge',
email: '*****@gmail.com',
image: 'https://cdn.discordapp.com/avatars/877175604431171644/11a34f62c10ed43957674fda26e80dcd.png'
},
expires: '2023-06-01T02:45:12.540Z'
}
USER {
id: 'clh5o2occ0000vhqscwd6tfer',
name: 'Børge',
email: '*****@gmail.com',
image: 'https://cdn.discordapp.com/avatars/877175604431171644/11a34f62c10ed43957674fda26e80dcd.png'
},
expires: '2023-06-01T02:45:12.540Z'
}
SESSION {
user: {
name: 'Børge',
email: '*****@gmail.com',
image: 'https://cdn.discordapp.com/avatars/877175604431171644/11a34f62c10ed43957674fda26e80dcd.png'
},
expires: '2023-06-01T02:45:12.540Z'
}
USER {
id: 'clh5o2occ0000vhqscwd6tfer',
name: 'Børge',
email: '*****@gmail.com',
image: 'https://cdn.discordapp.com/avatars/877175604431171644/11a34f62c10ed43957674fda26e80dcd.png'
},
expires: '2023-06-01T02:45:12.540Z'
}
How can i get the user's ID and discriminator?
24 Replies
abcdef
abcdef2y ago
@Børge Can you try to change it to this and see if the user object prints out the discord id and discriminator now?
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
profile: async (profile) => {
return {
id: profile.id,
discordId: profile.id,
discriminator: profile.discriminator,
};
},
}),
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
profile: async (profile) => {
return {
id: profile.id,
discordId: profile.id,
discriminator: profile.discriminator,
};
},
}),
Børge
Børge2y ago
Seems like nothing changed
abcdef
abcdef2y ago
Ah then I think ik why, lemme try something
abcdef
abcdef2y ago
@Børge
Børge
Børge2y ago
Don't really understand? Is that not the same session callback as mine?
abcdef
abcdef2y ago
You need to add the fields to the user model in the database when the user signs up / logs in
Børge
Børge2y ago
Okay, but the session and user in the session callback, are they not still going to be the same (without id and discriminator) or...?
abcdef
abcdef2y ago
user is the user object returned from the database If you have a discordId and discriminator in your db model it's gonna be in the object as well
Børge
Børge2y ago
I don't really understand This is my prisma model for user, if you mean that:
model User {
id String @id @default(cuid())
name String?
email String? @unique
image String?
discordId String? @unique
discriminator String?
accounts Account[]
sessions Session[]
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
image String?
discordId String? @unique
discriminator String?
accounts Account[]
sessions Session[]
}
And when i print the user in session callback, i just get null
USER {
id: 'clh5o2occ0000vhqscwd6tfer',
name: 'Børge',
email: '*****@gmail.com',
image: 'https://cdn.discordapp.com/avatars/877175604431171644/11a34f62c10ed43957674fda26e80dcd.png',
discordId: null,
discriminator: null
}
USER {
id: 'clh5o2occ0000vhqscwd6tfer',
name: 'Børge',
email: '*****@gmail.com',
image: 'https://cdn.discordapp.com/avatars/877175604431171644/11a34f62c10ed43957674fda26e80dcd.png',
discordId: null,
discriminator: null
}
abcdef
abcdef2y ago
Did you set it in the signIn method? Update the signIn method to first check if the user exists. If not, create a new user including the discordId and discriminator. Then remove the user from your database and sign up again. @Børge
Børge
Børge2y ago
Im trying to set it up, but i keep getting this error.
Inconsistent query result: Field user is required to return data, got `null` instead.
at pn.handleRequestError (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:176:6649)
at pn.handleAndLogRequestError (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:176:5907)
at pn.request (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:176:5786)
at async t._request (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:179:10484)
at async getSessionAndUser (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@next-auth\prisma-adapter\dist\index.js:226:36) {
name: 'GetSessionAndUserError',
code: undefined
Inconsistent query result: Field user is required to return data, got `null` instead.
at pn.handleRequestError (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:176:6649)
at pn.handleAndLogRequestError (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:176:5907)
at pn.request (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:176:5786)
at async t._request (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@prisma\client\runtime\library.js:179:10484)
at async getSessionAndUser (C:\Users\William\Desktop\Projects\McStore\mcstore\node_modules\@next-auth\prisma-adapter\dist\index.js:226:36) {
name: 'GetSessionAndUserError',
code: undefined
This is my current code:
async signIn({ profile }) {

const id = profile.id
const user = await prisma.user.findUnique({
where: { id }
})

if (!user) {

console.log("CREATING USER")
await prisma.user.create({
data: {
discordId: profile.id,
name: profile.username,
discriminator: profile.discriminator,
email: profile?.email,
avatar: profile?.avatar,
}
})
}

return true
},
async signIn({ profile }) {

const id = profile.id
const user = await prisma.user.findUnique({
where: { id }
})

if (!user) {

console.log("CREATING USER")
await prisma.user.create({
data: {
discordId: profile.id,
name: profile.username,
discriminator: profile.discriminator,
email: profile?.email,
avatar: profile?.avatar,
}
})
}

return true
},
abcdef
abcdef2y ago
Looks like something is wrong with the id Oh yea const id = profile.id is the discord id You should use the discordId field when querying the user since that's the field you're assigning the profile.id to.
async signIn({ profile }) {
const discordId = profile.id;

const user = await prisma.user.findUnique({
where: { discordId }
})

if (!user) {
console.log("CREATING USER");

await prisma.user.create({
data: {
discordId: profile.id,
name: profile.username,
discriminator: profile.discriminator,
email: profile?.email,
avatar: profile?.avatar,
}
});
}

return true
}
async signIn({ profile }) {
const discordId = profile.id;

const user = await prisma.user.findUnique({
where: { discordId }
})

if (!user) {
console.log("CREATING USER");

await prisma.user.create({
data: {
discordId: profile.id,
name: profile.username,
discriminator: profile.discriminator,
email: profile?.email,
avatar: profile?.avatar,
}
});
}

return true
}
@Børge
Børge
Børge2y ago
Okay that worked. So now I got it working, where it creates the user in the DB, but it redirects me to /api/auth/signin?error=OAuthAccountNotLinked.
abcdef
abcdef2y ago
That probably means there is another user with the same email in the db already @Børge Check if you can find another user with the same email and remove it
Børge
Børge2y ago
I'm the only one in the database
abcdef
abcdef2y ago
🤔
Børge
Børge2y ago
I also just tried to delete my self, and then login again, and i got redirected to the same page My full code at the moment, if that can help
import NextAuth from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET
})
],
callbacks: {
session({ session, user}) {

console.log("SESSION", session)
console.log("USER", user)

return session;
},

async signIn({ profile }) {
console.log(profile.id)
const discordId = profile.id;

let user = await prisma.user.findUnique({
where: { discordId }
})

if (!user) {
console.log("CREATING USER");

await prisma.user.create({
data: {
discordId: profile.id,
name: profile.username,
discriminator: profile.discriminator,
email: profile?.email,
avatar: profile?.avatar,
}
});
}

return true
}
}
});
import NextAuth from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET
})
],
callbacks: {
session({ session, user}) {

console.log("SESSION", session)
console.log("USER", user)

return session;
},

async signIn({ profile }) {
console.log(profile.id)
const discordId = profile.id;

let user = await prisma.user.findUnique({
where: { discordId }
})

if (!user) {
console.log("CREATING USER");

await prisma.user.create({
data: {
discordId: profile.id,
name: profile.username,
discriminator: profile.discriminator,
email: profile?.email,
avatar: profile?.avatar,
}
});
}

return true
}
}
});
abcdef
abcdef2y ago
Do you have an Account model in your schema? Account + User
Børge
Børge2y ago
Yes, Account, Session and User
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? @db.Text
session_state String?

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([provider, providerAccountId])
}

model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
id String @id @default(cuid())
discordId String @unique
discriminator String
avatar String?
name String?
email String? @unique
image String?
accounts Account[]
sessions Session[]
}
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? @db.Text
session_state String?

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([provider, providerAccountId])
}

model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
id String @id @default(cuid())
discordId String @unique
discriminator String
avatar String?
name String?
email String? @unique
image String?
accounts Account[]
sessions Session[]
}
abcdef
abcdef2y ago
Ah you need to remove it too
Børge
Børge2y ago
Remove Account?
abcdef
abcdef2y ago
Wait is there a allowDangerousEmailAccountLinking option for DiscordProvider? If so, try to set it to true
Børge
Børge2y ago
I just tried it, and it seems to be redirecting me correctly now.
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
allowDangerousEmailAccountLinking: true,
})
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
allowDangerousEmailAccountLinking: true,
})
Everything seems to be working - thx a lot!
abcdef
abcdef2y ago
👍
Want results from more Discord servers?
Add your server