Next.js Discord

Discord Forum

Update next auth current session from next api

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
Hi, I want to update the current session of next auth from next api. I'm making a external call from server and want to update the session there so it can be accessible in client side. Is there a way? Im trying with directly updating the session but it is not reflecting in client side.

Code:

const GET = async (req: NextRequest) => {
try {
const code = req.nextUrl.searchParams.get('code')
let session = await getServerSession(authOptions)
const redirect_uri = 'http://localhost:3000/api/discord/callback'
const apiUrl = 'https://discord.com/api/oauth2/token'

if (!code)
return new NextResponse('Code is required', {
status: 400,
})

const response = await fetch(apiUrl)

const data = await response.json()
const { access_token } = data

const userDiscordId = await getUserId(access_token)

// SESSION UPDATE ***
if (session?.user) {
session.user.discordId = userDiscordId
console.log('Updated the session', session)
}
} catch (error) {
console.log('Error: Got error authorizing with discord', error)
} finally {
redirect('/redirecting')
}
}

export { GET }
>

45 Replies

@Spectacled bear Hi, I want to update the current session of next auth from next api. I'm making a external call from server and want to update the session there so it can be accessible in client side. Is there a way? Im trying with directly updating the session but it is not reflecting in client side. Code: > const GET = async (req: NextRequest) => { > try { > const code = req.nextUrl.searchParams.get('code') > let session = await getServerSession(authOptions) > const redirect_uri = 'http://localhost:3000/api/discord/callback' > const apiUrl = 'https://discord.com/api/oauth2/token' > > if (!code) > return new NextResponse('Code is required', { > status: 400, > }) > > const response = await fetch(apiUrl) > > const data = await response.json() > const { access_token } = data > > const userDiscordId = await getUserId(access_token) > > // SESSION UPDATE ******************************************* > if (session?.user) { > session.user.discordId = userDiscordId > console.log('Updated the session', session) > } > } catch (error) { > console.log('Error: Got error authorizing with discord', error) > } finally { > redirect('/redirecting') > } > } > > export { GET } >
If you are using jwt tokens, that are saved only on the client, then only your client can change them with a request to the server, maybe some verification, that he is allowed to change his session and then it's changed. You can't change your client jwt's, when they are valid and saved only clientside
@Spectacled bear I'm not using jwt, I've a session object which I want to update
then your session data is inside your database, so you can directly update your database
Spectacled bearOP
I've to append a new property to session. Which im not able to do
yea and I am saying to you, that you can update your database to add the new property to your session
Spectacled bearOP
I'm sorry im not getting it clearly, how would i get a updated session by updating my db?
session based auth = user get's a token to a database entry and this database entry contains all information and all properties.

jwt based auth = a signed (and maybe encrypted) json object is saved on the users pc. You can't update it, while it's valid.
You said you are using a session based auth, so all your information is inside your db and can be updated directly
Spectacled bearOP
I don't want to store this value in db. It is a discord token which i want to add to session so that client can take it and use it.
Without adding to db, how could i update the session?

Like in client side we get a function update() which we can use to update our current ongoing session, same i want to do it from server side,
you discord provider looks like this, right?
import DiscordProvider from "next-auth/providers/discord";
...
providers: [
  DiscordProvider({
    clientId: process.env.DISCORD_CLIENT_ID,
    clientSecret: process.env.DISCORD_CLIENT_SECRET
  })
]
...
alright. And you have any adapter inside your configuration?
@B33fb0n3 alright. And you have any adapter inside your configuration?
Spectacled bearOP
I'm logged in via Google, so now the requirement is to load the user servers from Discord. Earlier I was logging the user via Discord and getting the list of servers of users, but that was overriding the Google session with a newly logged-in Discord session. To overcome this, I managed to do this manually i.e. authorizing discord so it doesn't update the session. I need one ID from the response of Discord that is the user's Discord and that I want to append to the session so that I can access the user's server at a later time.
Spectacled bearOP
coz it would override the current session. This would be a issue if both Google and Discord accounts are on different emails.
you are right, it would overwrite the session. But for what do you need to use google. What about only using discord login, because you need it for the id?
Maybe I am not seeing the sense of using google right now
Spectacled bearOP
The app has the functionality to provide multiple login providers. Not my call 🥲
ahhhh got it
Spectacled bearOP
Thanks, any idea how could I update the session on server side?
yes I have an idea how I would do it. You using a database?
Spectacled bearOP
Yes but not storing that property value in db
Alright. If I would be you, I would create a multiple tables:
- account: store all authO providers inside this table with that any user logged in. There are some fields about the provider itself like email, image, ... and also a userId or whatever you call it.
- user: this table stores personal information about the user. Like firstname, lastname, ... and of course discordId.

So account is for login stuff and user is for information stuff.

When you create the session with the google provider you also get the userId (because it's as key inside the account table). When updating the discordId inside your usertable, you also directly update the clients session, because the client itself only stores a key to the specific data (userId)
It could look like this (ignore the green lines)
Brown bear
const GET = async (req: NextRequest) => {

It's server side code
 // SESSION UPDATE ***
        if (session?.user) {
            session.user.discordId = userDiscordId
            console.log('Updated the session', session)
        }

So this code can't be update the session of client side

##Solution:
Please return the userDiscordId to client side and update the session on request part of client side
for example
axios.get('/api/getDiscordID').then(({data})=>{
  const userDiscordId = data.userDiscordId 
 // SESSION UPDATE ***
        if (session?.user) {
            session.user.discordId = userDiscordId
            console.log('Updated the session', session)
        }
}
@Brown bear for example axios.get('/api/getDiscordID').then(({data})=>{ const userDiscordId = data.userDiscordId // SESSION UPDATE *** if (session?.user) { session.user.discordId = userDiscordId console.log('Updated the session', session) } }
I already told him, that only the client can update the jwt, but he said he using sessions.

And he also want to update it serverside. And real sessions can be updated serverside
Spectacled bearOP
I can update it on the client side but I just want to know if there is a way otherwise I'll go with the client side.
If there is a way I'll do it from sever side else I'll try to do it client side
But there has to be some way on server side to update the session
Brown bear
Of cause, serverside has session. but it can't be reflecting with client side(on broswer)
So have to use callback on client side
@Brown bear Of cause, serverside has session. but it can't be reflecting with client side(on broswer) So have to use callback on client side
it can. You ever heard about normal sessions? There are serverside handled only. See here: https://miro.medium.com/v2/resize:fit:1400/1*Hg1gUTXN5E3Nrku0jWCRow.png

If he use jwt, then you are right. Then only the client can initiate an update to the server and the server can apply the update or deny the update.

But he said, that he is not using jwt: https://nextjs-forum.com/post/1244932709319573528#message-1244937601857622066
Spectacled bearOP
Thanks guys, I'm moving ahead with sending the field to client side and updating it there.
But help me clear one thing.

The session that we get using useSession() can we access that session in our next api side?
@Spectacled bear But help me clear one thing. The session that we get using useSession() can we access that session in our next api side?
Yea, it’s the same when you access it serverside via:
const session = getServerSession(authOptions)
Spectacled bearOP
I'm confused now, why I was not able to update this session on server side!
@Spectacled bear I'm confused now, why I was not able to update this session on server side!
Because the client holds the data and the server just sign it
@Spectacled bear I'm confused now, why I was not able to update this session on server side!
Brown bear
Nextjs is Fullstack framework, which is using React and Nodejs
So Just think they are separate to Frontend and Backend
Tonkinese
Am I understanding that right, that you also tried update the tokens of discord?
Like when they expire
@Brown bear Nextjs is Fullstack framework, which is using React and Nodejs So Just think they are separate to Frontend and Backend
Spectacled bearOP
That means even though they can access the session but backend can not update the session?
@Spectacled bear That means even though they can access the session but backend can not update the session?
Your backend can give them new signed data. But that works only on request of the client, because this new data need to be set somewhere (to explain it as easy as possible).
So just do it clientside.
@Spectacled bear solved?