Cookie authentication
Unanswered
Broad-snouted Caiman posted this in #help-forum
Broad-snouted CaimanOP
I'm using an api through cors that I authenticate against using http-only cookie authentication:
- Request the "/login" endpoint with credentials from a client component.
- Receive a response with a Set-Cookie header that sets an auth cookie in the browser/client.
- The auth cookie is sent with all upcoming requests from the client.
The cookie authentication is working as intended as long as I only make requests from client components. But whenever I make a request from server components they don't include the auth cookie.
How is this (cookie auth) typically handled in next.js to share this cookie between client and server components?
- Request the "/login" endpoint with credentials from a client component.
- Receive a response with a Set-Cookie header that sets an auth cookie in the browser/client.
- The auth cookie is sent with all upcoming requests from the client.
The cookie authentication is working as intended as long as I only make requests from client components. But whenever I make a request from server components they don't include the auth cookie.
How is this (cookie auth) typically handled in next.js to share this cookie between client and server components?
7 Replies
Black-and-white Warbler
Having the same problem. Is there any fix for this?
@Black-and-white Warbler Having the same problem. Is there any fix for this?
European sprat
Create your own post with code, errors, details of what you've tried and are trying to accomplish
@European sprat Create your own post with code, errors, details of what you've tried and are trying to accomplish
Black-and-white Warbler
it's literally the same case as the one described above, try to login (set an httpOnly cookie in the browser via a fetch call to an express server). Set cors and all that, working fine for pages if they're "use client" pages. But if it's server component cookie is not being set.
Asian black bear
You could forward the cookie from the component request to your fetch for the api
Asian black bear
Also fetch in server components can not use endpoints in your next app
@Asian black bear Also fetch in server components can not use endpoints in your next app
Broad-snouted CaimanOP
It's an external api that responds with a Set-Cookie header containing the token. Therefore the token is not reachable from within the client/browser. However, you could forward the login request through your own route handler endpoint and get access to the cookie on the server, then forward it to your client with a correct domain property. But how would I then also use this cookie/token from my server rendered components for subsequent requests to the external api?
@Black-and-white Warbler did you reach a conclusion?