Best Approach for Handling JWT in Next.js with a Separate API Server (Server Actions vs. Direct API)
Unanswered
North Pacific hake posted this in #help-forum
North Pacific hakeOP
If we use Server Actions or API Routes in the client (browser), would that generate traffic to the Next.js server? If so, in an architecture where we have a separate API server, would handling authentication via Server Actions or API Routes be the best approach?
For example, after making a login API request, the token is returned via the Set-Cookie header and JSON response.
If the token is stored in an HttpOnly cookie, future API requests requiring authentication won’t be able to access it directly from the browser. In this case, we would need to retrieve the token from the Next.js server, likely using Server Actions or API Routes.
However, as mentioned above, this means traffic would be generated on both the Next.js server and the API server. In that case, wouldn't it be better for the browser to request the API directly? But since HttpOnly cookies cannot be accessed in the browser, we would have to change the cookie settings.
Given this situation, what would be the best approach?
I’d appreciate any insights or recommendations.
For example, after making a login API request, the token is returned via the Set-Cookie header and JSON response.
If the token is stored in an HttpOnly cookie, future API requests requiring authentication won’t be able to access it directly from the browser. In this case, we would need to retrieve the token from the Next.js server, likely using Server Actions or API Routes.
However, as mentioned above, this means traffic would be generated on both the Next.js server and the API server. In that case, wouldn't it be better for the browser to request the API directly? But since HttpOnly cookies cannot be accessed in the browser, we would have to change the cookie settings.
Given this situation, what would be the best approach?
I’d appreciate any insights or recommendations.