0

I need some help in understanding how cookies are managed in Angular. I am using ngx-cookie-service to generate a cookie for my web app. What isn't clear to me is that since angular run in my browser, actually the browser should set the cookie when I use cookieService.setCookie(...). But if it's the case, where is that cookie sent? To which server?

I would say the cookie should be sent to the web server, for example http://localhost:4200, but if the cookie is created from my browser, how can the server be aware of it?

I'm speaking about Angular, but I can formulate the same question more generally to every web applications.

dc_Bita98
  • 851
  • 2
  • 17
  • 35

1 Answers1

1

Cookies are stored by the user's browser, regardless of whether the cookie is set via a header received from a http(s) call, or via a setCookie() api call in the client JavaScript.

Cookies are segregated by the domain that has set them, and can be further segregated by the "page" that set them (less meaningful in an SPA app).

In a simple, static web page, the browser will send further http(s) requests with the cookies are "in scope" for the current domain, page, etc.

However, the Angular HttpClient does not, by default, send cookies when you make an Http(s) call. You have to enable this explicitly.

For more info, see Angular HttpClient does not send domain cookie

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • First of all, thank you, you may have enlightened me. I need to asses whether I've understood: so, if I stored a JSON Web Token in a cookie on an Angular web app, that JWT wouldn't be appended to each and every single request made by my browser to the Angular server at `http://localhost:4200`, right? That cookie wouldn't go anywhere, we could call that cookie something like "local -only" cookie", couldn't we? – dc_Bita98 Oct 11 '20 at 18:11
  • 1
    Yes, that's my understanding. However, if you're going to keep it "local only", then there's no reason to use a cookie, you can just use localstorage, which would be a more usual to thing to do in that situation. – GreyBeardedGeek Oct 12 '20 at 02:26