I am building a full-stack application with NodeJS-Express-TypeScript on the backend and Nuxt 3 on the frontend. In the backend, I have 3 API routes to handle user authentication (signup, sign-in and profile APIs). To sign in the user makes a post request to the server which validates the request. If the validation is successful, the server creates a session and returns an accessToken and refreshToken as cookies like so:
res.cookie('accessToken', accessToken, {
maxAge: 900000, // 15 mins
httpOnly: true,
domain: 'localhost',
path: '/',
sameSite: 'strict',
secure: false,
});
res.cookie('refreshToken', refreshToken, {
maxAge: 3.154e10, // 1 year
httpOnly: true,
domain: 'localhost',
path: '/',
sameSite: 'strict',
secure: false,
});
return res.send({ accessToken, refreshToken });
From the code above, you can see that it also sends those tokens as responses to the frontend.
My problem comes with how to retrieve the response cookies. Per the Nuxt documentation, useFetch would be the preferred way to make this call. The problem however is that useFetch DOES NOT return the cookies in the data value. Try as much as I may, useFetch will simply not return the response cookies. It will however return the tokens sent in the response body but that is of little value as I cannot create HTTP-only cookies on the frontend.
The Nuxt documentation mentions using the useCookie composable but if I understand the docs correctly, the use case for that comes in when I am creating my server inside of Nuxt which I am not.
If I use $fetch instead, I get the cookies, but this raises its own set of problems. For starters, with useFetch, I can handle specific error codes that my backend sends back if authentication fails but I can't do this with $fetch (or I probably don't know how to). Secondly, when using $fetch to perform the signup action, somehow my backend doesn't throw a 409 conflict if the email already exists in the database, which it should and does do when using useFetch. It simply goes ahead and creates a new record in the database with the same email leading to duplicate emails. I don't know how this is happening but it is. This Reddit post outlines something similar https://www.reddit.com/r/Nuxt/comments/13th0cu/how_to_set_cookies_in_nuxt_3/?rdt=43472&onetap_auto=true but here the OP uses Axios. I don't want to use Axios.