Skip to content

Instantly share code, notes, and snippets.

@deefdragon
Last active November 30, 2020 01:12
Show Gist options
  • Save deefdragon/96edde1fb21e09dc87a8db3ed473f36b to your computer and use it in GitHub Desktop.
Save deefdragon/96edde1fb21e09dc87a8db3ed473f36b to your computer and use it in GitHub Desktop.
Cookies not sent to api over websocket, ngx-cookie-service
TLDR: add {withCredentials: true} to the options sent in the request. In angular I had to create an interceptor to do the job.
I have been fighting with my server, attempting to send a UUID with my requests to give my non-logged in clients some kind of persistance. I started with passing it as a header, but because one of my requests uses web-sockets, I cant use headers for everything. This means that I have to use a cookie for the requests. I would have rather used the header, but whatever.
Storing the cookie is important anyway because the UUID should be stored between requests. As such, on every request, the UUID is checked, and if it doesent exist, the cookie is created. The header is then added to the request where needed.
For most of the calls, I had already created an interceptor that would generate a header to add to the calls. Because websockets dont keep headers (WHY was that a decision made when you literally upgrade the protocol I DONT know, but I digress) I had to use a cookie, or come up with a handsake. I would like to avoid the handshake as it makes it so much more implementation specific than I would like.
Therefore I need to send a cookie with the request. Im comes `this.cookieService.set("sub", newID, 20000, '/', '', false, 'Lax');` Which I spent hours debugging as to why the cookie was not sending. I even upgraded both my host and api into https to test it(keeping it, but I do wish I didnt waste so much time). It turns out however, that I am just an idiot. when making external requests, to include the cookies, you have to add the withCredentials flag. Setting this on the requests made everything work again.
The even worse thing? Had I not altered server side to only accept cookies, It would have worked as that flag is not needed on websockets. /shrug I guess.
I will be updating my ID check middleware to look for the header first, and if it does not exist, the cookie, as that to me is the way to make sure it always works, and that I dont have to worry about adding the flag to all calls in the future. Only the ones that dont allow headers (which are few and far between I expect, but meh).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment