Set-Cookies Header and withCredentials
I have been working on a little app recently to understand authentication both from the Frontend and also the Backend. On the backend I am using Nestjs and on the Frontend I am using Nextjs.
If you interested in seeing the code you can check out the Github repos below (WIP btw)
Github Repo — Backend
Github Repo — Frontend
One new thing I learnt during the process of learning about authentication was the Set-Cookie Http response header. It can be used when generating cookies for auth tokens on the backend and then setting headers for ‘Set-Cookie’ on the response and sending them through to the Frontend.
It can be used when generating cookies for auth tokens on the backend and then setting headers for ‘Set-Cookie’ on the response and sending them through to the Frontend.
You can see an example function on the backend used to generate and sign an auth token and return a string ready to be sent back in the response:
I couldn’t work it out for a while. So I did what any good dev does… I started googling it.
A Problem I ran into
One problem I ran into though was when this response was being sent back to the client the Cookie was not being set in the browser! I couldn’t work it out for a while. So I did what any good dev does… I started googling it. I found a couple of useful stack overflow questions:
From reading both questions it was pretty likely that my problem lay with some CORS setting.
My Frontend was running on http://localhost:3000 and my backend was running on http://localhost:3003. Therefore there was a couple of adjustments I had to make on both the Backend AND the Frontend:
But I also had to make some update on the axios request on the Frontend:
After reading a bit more I understood why this was the case. This
withCredentials property is a boolean that indicates whether or not a cross-site
Access-Control requests should be made using credentials such as cookies. For more info see the mozilla docs and also this Stack Overflow question.
Once these CORS updates were done the cookies started to be set in the browser and my requests from the Frontend could be properly authenticated by the backend! Woohoo!
I love making small apps to focus on specific skills and then learning these little nuggets of information along the way. I am pretty sure without continually developing and trying new things I wouldn’t know about this particular property and would continue to live in ignorance.
I hope you enjoyed the article and please let me know any comments or questions!