Is there a better way of handling cookies in server actions for authentication with custom backend?
Unanswered
Mini Lop posted this in #help-forum
Mini LopOP
Hello, recently I started building a project using NextJS (app router), and struggled when dealing with cookies for authentication (with a separate backend). I finally found a solution for setting and sending cookies in NextJS.
At first I thought, when the backend return a response with a Set-Cookie header in it, it will automatically passed on to the browser. But this is not the case, I have to get the value of the Set-Cookie header response, it was something like this:
And I have to parse the string and set it manually using the
Another problem is for some restricted pages (that requires user to sign in), I need to make a request to the custom backend if the user is signed in, that requires me to send the cookies again. For this, I have to manually get the access token again from the
Is there a better way to deal with cookies in NextJS without manually getting and setting the cookies?
At first I thought, when the backend return a response with a Set-Cookie header in it, it will automatically passed on to the browser. But this is not the case, I have to get the value of the Set-Cookie header response, it was something like this:
"set-cookie": [
"accessToken=${value}; Path=/; HttpOnly; SameSite=Lax",
"refreshToken=${value}; Path=/; HttpOnly; SameSite=Lax"
]And I have to parse the string and set it manually using the
cookies function in NextJS. Another problem is for some restricted pages (that requires user to sign in), I need to make a request to the custom backend if the user is signed in, that requires me to send the cookies again. For this, I have to manually get the access token again from the
cookies function and then manually include the token inside the cookie header. And I have to do this repeatedly for any api calls that requires cookies to be sent.Is there a better way to deal with cookies in NextJS without manually getting and setting the cookies?