I am working on a mini project with Next-Auth
(with credentials), I have the following scenario:
const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
id: 'credentials',
name: 'credentials',
credentials: {},
async authorize(credentials) {
const { email, password } = credentials as { email: string; password: string }
const uuid = uuidv4()
const res = await fetch("https://myapi.blabla/api/v9/accounts/sign-in/", {
headers: {
Authorization: `uuid ${uuid}`,
"Client-Id": "vrfyrvKmSIRs8s1BZuHcmHNaZuTR2nIF0ZgFt39",
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify({
email,
password
})
})
const user = await res.json()
if (!res.ok) {
throw new Error(user.message)
}
// If no error and we have user data, return it
if (res.ok && user) {
return user
}
// Return null if user data could not be retrieved
return null
}
})
],
pages: {
signIn: '/login'
},
callbacks: {
jwt: async ({ token }) => {
return token
},
session({ session, user }) {
return { ...session, ...user }
},
}
}
If I console.log const user = await res.json()
the response is:
{
"advertising_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"api_key": "xxxxxxxxxxxxxxxxxxxxx",
"username": "xxxxxxx",
"session": "xxxxxxxxxxxxxxxxxxxxx"
}
The problem is, when I use const session = useSession()
in the front, I only get:
{
session: {
user: {
name: undefined,
email: '[email protected]',
image: undefined,
},
expires: '2023-04-09T14:53:56.395Z'
}
}
And I need the response should be something like:
{
session: {
user: {
name: undefined,
email: '[email protected]',
image: undefined,
session: 'xxxxxxx-xxxxxxxxxxxx',
advertising_id: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
etc...
},
expires: '2023-04-09T14:53:56.395Z'
}
}
Am I doing something wrong? Am I missing something? Or do I need a different mechanism to be able to send the session information to the client?
2
Answers
Thank you very much, that works perfect! My previous approach also worked for me:
I see a few missing things:
When creating
CredentialsProvider
you should have passedIf inside authorize, you are returning
user
, that user will be passed tojwt
callbackthen this token will be passed to the
session
callbackYou can see an example setup