Setting cookies in next server components while working with external api #81790
-
SummaryI am working with external api that has token based auth. When i login using server action the server responds with the token which i save in http only cookies. And when i need to fetch the data in server components i get the token from cookies and send the token with the request. Just to let you know i am not using route handlers to proxy requests i am using fetching data directly in server components. Now every thing works till now until unless i need to handle the case of token expiry or when my server responds with 401 or 403 now in this case i need to logout the user and clear the cookies but as i am in server components i cannot do that since we can only modify the cookies in server actions and route handlers. So now i feel stuck and dont know what to do. Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
you are correct that you cannot modify cookies directly in your normal response. First question - is the logged in status fully dependent on the validity of the token you are getting from a 3rd party API? If so, I would always first check the validity, ideally in the root of the component tree, i.e. in the export default async function ProtectedPage() {
const token = await cookies().get('token')?.value
if (!token || isTokenExpired(token)) {
redirect('/logout') // Triggers cookie clear and redirects to /login
}
// Continue rendering...
} // app/logout/route.ts
export async function GET() {
const response = NextResponse.redirect('/login')
response.cookies.set('token', '', {
path: '/',
maxAge: 0,
httpOnly: true,
secure: true,
})
return response
} |
Beta Was this translation helpful? Give feedback.
-
hey @maral thanks for the reply. I have a confusion, Are you suggesting to redirect to a route(page) |
Beta Was this translation helpful? Give feedback.
Hi, sure you can cache it to a cookie or even to local storage, whatever is more comfortable. However if it changes, you might display deprecated information, so you need to implement some kind of cache invalidation or update it after while.
You're welcome :) Make sure to mark your question as answered.