Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refreshing token on server component with API route #884

Open
kemalatila opened this issue Dec 6, 2024 · 1 comment
Open

Refreshing token on server component with API route #884

kemalatila opened this issue Dec 6, 2024 · 1 comment

Comments

@kemalatila
Copy link

kemalatila commented Dec 6, 2024

First of all, let me state I use both server components and client components in my project on NextJS.

I can easily obtain the access token from the /oauth/token API route and save it with iron-session with client component -> api route request, but I encounter errors when using server-side components when trying to refresh the token.

I set the axios request with the cookie header because when I send a request from the server-side component to the API route, it isn't able to read the cookies if I don't provide them.

  const response = await httpClient.get('/oauth/token', {
     headers: {
       Cookie: `authSession=${authSessionCookie.value}`,
     },
   })
    authSession.refreshToken = response.data.refresh_token
    authSession.accessToken = response.data.access_token
    authSession.expiresIn = response.data.expires_in
    await authSession.save()

    let res = NextResponse.json({ success: true, data: response.data })
    res.headers.set('Set-Cookie', cookies().toString())

    return res

But it doesn't set cookies with set-cookie header on the response. I know the issue not about iron-session library but maybe you can offer better way to implement the library and for solve the issue.

@kemalatila
Copy link
Author

kemalatila commented Dec 6, 2024

I have also tried to save cookies with returned data from API routes with this function but I get this error

Server Component calling server action getting Cookies can only be modified in a Server Action or Route Handler

'use server'

import { sessionOptions } from '@/config/CookieConfig'
import { SessionData } from '@/types/AuthService'
import { getIronSession } from 'iron-session'
import { cookies } from 'next/headers'

export async function setCookie(data: any) {
  const authSession = await getIronSession<SessionData>(cookies(), sessionOptions)
  authSession.accessToken = data.access_token
  authSession.refreshToken = data.refresh_token
  authSession.expiresIn = data.expires_in
  await authSession.save()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant