Cookie based auth with nuxt auth utils
I have a server which is sets a cookie on login and then that cookie is needed to authenticate users for other requests.
I'm creating a frontent application with nuxt and just wondering what happens to the cookie if the server is sending the login request? Will the cookie be set for the user or do I need to make the call from client side?
2 Replies
Hi @LordGhandi. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
When using Nuxt and a cookie-based authentication system (such as with nuxt-auth-utils), whether the cookie is set for the user depends on where the login request is made from:
- If the login request is made from the client side (browser):
The server's
The
However, if you make an internal server-to-server request (e.g., using
- For login requests from the client: cookies are set automatically. - For login requests from the server: you must forward the
The server's
Set-Cookie
header will be received by the browser, and the cookie will be stored automatically. This is the standard behavior for browser-based HTTP requests.
- If the login request is made from the server side (during SSR or in a server API route):The
Set-Cookie
header is sent in the server's response to the browser. As long as you return the response from your API route or page, the cookie will be set in the user's browser.However, if you make an internal server-to-server request (e.g., using
$fetch
or useFetch
on the server to call your own login API), the cookie will not be automatically set in the user's browser. In this case, you need to manually forward the Set-Cookie
header from the internal response to the actual HTTP response sent to the client. This can be done using utilities like appendResponseHeader
from h3
:
This ensures that cookies set by your internal API are actually sent to the user's browser in the final response. This pattern is documented in the Nuxt docs and is necessary for SSR or API proxying scenarios where you want the user's browser to receive authentication cookies set by your backend API Docs: Passing Headers and Cookies.
Summary:- For login requests from the client: cookies are set automatically. - For login requests from the server: you must forward the
Set-Cookie
header to the client for the cookie to be set in the browser.
This approach is compatible with nuxt-auth-utils
, which uses cookies for session management Sessions and Authentication.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@358749735323959308> Kapa.ai is still learning and improving, please let me know how I did by reacting below.