How can you create cookies in Angular 6? For AngularJS there was ngcookie
. What is the equivalent way to create cookies in Angular 6?
-
1I'm a little bemused as to why this question has been shut down. It's a valid, succinct question that lots of people upvoted with perfectly valid answers. The modding here sometimes feels a little bit like snipers who haven't been told that the war is over. Just come down from the trees guys – Peter Nixey Jul 13 '20 at 09:51
-
@PeterNixey Just because a lot of people have voted/answered doesn't necessarily mean the question itself is good. Keeping questions like this open sends a message to new users that unfocused questions like "How do I do X" without showing self-research or attempted solutions are oké and on topic. A lot of people pass speed limits, but that doesn't make speeding good. – Remy Jul 13 '20 at 12:32
-
@remy that's reasonable but I don't see how the question is outside the speed limits. It's incredibly specific - it's referring to a particular utility in AngularJS and askign what the equivalent is in Angular 6. My original question was slightly flippant but I genuinely don't see how that is unfocussed – Peter Nixey Jul 13 '20 at 12:39
-
@PeterNixey I can see your point that likey "unfocussed" isn't the proper close reason, and agree (it is indeed specific). However since we (normal users) can't change the *reason* for closing I still voted to keep it closed, for the above reasons. (I would probably personally go for "needs debugging details", as there seems to be no effort made to solve it prior to asking). But I think your raised point is certainly valid. – Remy Jul 13 '20 at 13:07
4 Answers
npm install ngx-cookie-service --save
- Add to your module:
import { CookieService } from 'ngx-cookie-service';
- Add
CookieService
to module's providers. - Inject it into your constructor.
- Use
cookie.get(nameOfCookie)
for getting a specific cookie, usecookie.set(nameOfCookie,cookieValue)
for adding a new cookie.
-
5I believe you forgot to mention about adding it to the app module. In your `@NgModule` add it as a provider `providers: [ CookieService ]` – CodeWarrior Aug 24 '18 at 01:58
-
[ts] Cannot find module 'ngx-cookie-service'. [2307] i try to npm i then ionic serve then error occurred – saber tabatabaee yazdi Feb 08 '19 at 23:48
-
@CodeWarrior From angular 5(or 6) and onwoards you don't have to add the service in the providers – Manos Kounelakis May 29 '19 at 15:45
-
1@ManosKounelakis Yes mate, I was using Angular 4 at the time I made this comment. – CodeWarrior May 31 '19 at 07:51
You can use this node package for it

- 1,395
- 10
- 8
-
In angular you can simply use a local storage instead like localStorage.setItem(key,value); – Tuvia Khusid Aug 13 '19 at 01:31
-
You _can_ do that, but what if you want the value to get stored for like 10 mins and then disappear? Local storage wouldn't do that. – Mikefox2k Sep 13 '19 at 07:40
First of all, you should ask yourself: "Do I really need cookies ?" :
Cookies were once used for general client-side storage. While this was legitimate when they were the only way to store data on the client, it is recommended nowadays to prefer modern storage APIs. Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB. (Source: MDN)
So, if you haven't already, you may want to read about the Web Storage API instead.
If you do want to continue with cookies, please read on.
I tried ngx-cookie-service
and it didn't work for me. I had issue after issue, ended up discussing it on github, tried updating packages. It took me about a day to realize that what I needed did not have to be that complicated, after all getting/setting cookies is just a native javascript thing.
I had no more time to waste, and wrote this simple CookieService
myself. And I just wanted to share it with other desperate developers. :)
A simple CookieService
I created this gist , which is a lightweight alternative to ngx-cookie-service.
Setup and Usage
Of course you need to register it in your app.module.ts
file.
Add it to the list of your providers:
providers: [FooService, BarService, CookieService]
Next, use it in your components, e.g. as follows:
private _sessionId: string;
constructor(private cookieService: CookieService) {
this._sessionId = cookieService.get("sessionId");
}
public set sessionId(value: string) {
this._sessionId = value;
this.cookieService.set("sessionId", value);
}
Note that you can use the debug tools to verify that the cookie is actually set, and to verify that it is present in the subsequent HTTP requests. (screenshots of Chrome, but Firefox and Edge have similar overviews)
-
I tried using this to get a cookie's value, but got an incorrect value for it . The correct cookie was set in a get request via ```withCredentials: true ```. I want the cookie's value so I can send it in the header of a post request. I know I'm sending the correct cookie which is automatically set via withCredentials, but I need to send a header with the cookie's value. – danny gonzalez Jan 09 '19 at 23:15
-
1@dannygonzalez I assume that you checked it with your webbrowser debug tools. But in case you didn't, I added some screenshots of how you could double check it. - Not sure if this is helpful for you though. – bvdb Jan 10 '19 at 21:52
-
thanks. In my case, I want to read the HTTP response headers of the initial page request which I suppose is not possible to read (https://stackoverflow.com/questions/58950016/how-to-make-angular-application-read-cookies-at-start-up/58950610#58950610). What I intend to do is send a Cookie, read it the application using `document.cookies`. I suppose I can't do this using `localStorage` or `sessionStorage` because I'll still have to send the value I want to store as a cookie. Isn't it? – Manu Chadha Nov 20 '19 at 09:21
-
Please DO NOT use Localstorage for sensitive data like session tokens - it can be stolen with a simple cross-site scripting attack. Cookies can be suitable for this, thanks to the HTTP-Only flag, but then can only be set via the Cookie header. – Tom Mettam Nov 25 '19 at 06:55
-
@TomMettam I realize that my example of a session id is perhaps politically incorrect or at least open for debate. However, even though there have been discussions about this topic for years now, there is still no consensus about it, resulting in several open questions, like this one: https://security.stackexchange.com/questions/199527/should-sensitive-tokens-be-stored-in-localstorage-or-an-httponly-cookie – bvdb Nov 25 '19 at 10:18
-
1I would say that there's very good consensus about the issue, personally; If you google for "use localstorage for tokens" every single result is about this being a bad idea. However, that doesn't make your answer invalid.. from Angular, using HTTPOnly cookies is not an option - these can't be read or written by Javascript. So there is still no reason to use cookies over LocalStorage in this case. Therefore my comment wasn't a contradiction to your answer, but rather some advice to supplement it. – Tom Mettam Nov 25 '19 at 13:07
Now is: npm install ngx-cookie --save
-
4it is good to include links, but please share the steps to make the answer more useful – Akber Iqbal May 13 '19 at 03:32