Photo by Émile Perron on Unsplash

Cookies are small packages of information that can be temporarily stored/saved by your browser and websites which are using cookies for multiple things. They are often not more than a few kilobytes per cookie. Cookies are used in multiple requests and browser sessions and can store your account information used by authentication for example.

Installing dependency

For Angular, we have an already created NPM package called ‘ngx-cookie-service’ which can be used for working with cookies. Let install the package inside your repo as a dependency;

npm install ngx-cookie-service

Getting started

After installing the dependency, we can use it by import the CookieService inside one of our modules. In this example, we use the AppModule . Please add them as a provider;

Code display by Carbon

How to use

In the example code below, we are going to use our AppComponent and use the set and get method of the CookieService . We injecting this service in the parameters of the constructor. Inside the ngOnInit method, we set a new cookie and get that same cookie.

In the first line, we set a new cookie called cookie-name with some random value. On the second line, you can see how to get the cookie value;

Besides the get and set methods, there are more methods available inside this package like check , getAll , delete and deleteAll , they are showed in the example below. The set method has more optional parameters that can be filled than I showed in the above example. The expires parameter is advised to set. Otherwise, they can last forever.

That’s all!