How to set and save cookies in your frontend, most common issue.

Steve
1 min readMar 2, 2021

Most of the time, if you want to work with cookies, you will stumble across the same set of problems, and start to fight with CORS, headers policies and browser securities features.

Stop. That’s what I shall have told myself after spending 4 hours reading about these topics, while I just wanted to save my token, as a cookie, in my frontend. If your client will be hosted on the same domain as your backend, in production, you should not complicate things by changing your cors or overriding your browser normal behavior.

This solution applies to 90% of the “my cookies are not saved” or “Allow origin headers doesn’t accept wildcards” problems.

All of these issues come from the fact that, usually, in local development, you will serve your frontend and backend on different ports. Thus, CORS and browser will make your life very hard to work with cookies, on purpose. The simple solution is to set a proxy, so your frontend thinks the backend is served on the same domain.

For the most popular frontend framework, as React, it is as simple as editing your package.jsonwith the following line:

"proxy": "http://localhost:[YOUR BACKEND PORT]"

and directly calling your backend with a relative path like / instead of localhost:8000/

For other people over here (looking at you Vue hipsters and Angular oldies), just search how to set a proxy in google, shall be easy.

--

--