How to use Cookies in Angular.

Joy Sen
5 min readMay 21, 2020

The name which comes up in our head first hand when we heard about “Cookies“ is a specialized food baked with flour and egg that is one of the renowned food items in the whole world. But in the arena of web development, the name cookie is denoted with different meanings. To meet the different needs of most of the Apps & Websites a small chunk of data is stored in the client's devices. (if the data stored on the server-side is called the session which we will discuss in a separate article).This small data is called Cookies.

Cookies are used to store a small amount of important data in the client browser.

According to MDN
An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user’s web browser.

In terms of uses, these cookies can be used in several ways for example

For Logins: Shopping carts, game scores, User preferences, themes, and other settings.
For Tracking: Recording and analyzing user behavior.

In this article, we focus on how to use and implement Cookies in the Angular platform. Let’s start to learn it step by step process. To make the steps simple I have used lots of screenshots rather than text.

1. Firstly using the ng-new CLI command I have created a new project called “praccookie”.

Create a new project.

2. The next step is to create a component that is used to apply three prime mechanisms of cookie-
i) Set a cookie,
ii)Get a cookie,
iii)Delete a cookie.

create a component using ng cli command.

After that, in the praccookie HTML file I have created three buttons with three onClick event methods. I also add some CSS to make things a little bit prettier.

The HTML code.
CSS code

The next step is to compile the file using ng serve command and test on the browser.

After applying the code above output of the praccookie component.

3. Now install a 3rd party cookie package called NgxCookieService. Here is the link. We can install it by using npm or yarn, I am using npm, copy the line below, paste and hit enter into your terminal. It will install the package into your device locally.
npm i ngx-cookie-service@13.2.1

After the installation is complete, add some changes to the app module file. Add Cookieservice as a provider.

App module section
Screenshot from the package.json.

4. Let’s back to praccookie component, in the ts file import and inject it into a constructor.

Our all initial tasks have finished. It’s time to apply create, get, and delete the cookie functionality.

To set or create a cookie, use set function .In our context let use the code below
setcookiebtnn(){
this.cookieservice.set(“firstname”,”Joy”,{expires:2,sameSite: ‘Lax’});
}
the set function work like a key,value pair.In our code ‘firstname’ is cookiename and ‘joy’ is it’s value. expire of this cookie 2 days and the sameSite is ‘Lax’.

Important:

For security reasons, it is not possible to define cookies for other domains. Browsers do not accept cookies flagged sameSite = ‘None’ if secure flag isn’t set as well. CookieService will override the secure flag to true if sameSite=’None’.

Additional Note :

Basically SameSite cookie attribute is used by browsers to identify how third party cookies will be handled. It can be block or allow any cookie based on the senario.The sameSite cookie first introduced in February,2020, google chrome 80 version.

On our website, we have two options when establishing a SameSite cookie value:
Lax and strict.

Strict:
With the SameSite=strict value the web browser prevent the web browser prevents cookie data from being transferred during cross-domain requests in all instances.
Lax:
The “Lax” value in SameSite is a more relaxed form of cross-site request protection.

5.Compile our codes again using ng serve,it will run the code into the browser. Now click on setcookie button. It’s work!! A cookie named ‘firstname’ has stored in your browser, wait how can you be sure? To verify a cookie exits or not, ngxcookieservice has a function name check().

const cookieExists:boolean=this.cookieservice.check(“firstname”);
if(cookieExists){
console.log(“Find the cookie”);
}else{
console.log(“The cookie hasn’t set”);
}

As we can see the cookieExists check the availability of the “firstname” cookie.

The console indicate that the cookie has created successfully.

If we need the value of the cookie,we can use get() function.

The get() function return the cookie value.In here “firstname” is the cookie name. There is another function name getall() which is return all the available cookie values.

By using the get() function, we can get the cookie value.

Finally now we will learn about the delete() function, it’s same as the get and set method.

this.cookieservice.delete("firstname");

const cookieExists:boolean=this.cookieservice.check("firstname");

if(cookieExists){

console.log("Find the cookie");

console.log("The cookie value is "+this.cookieservice.get("firstname"))

}else{

console.log("The cookie isn't exist..");

}

here “firstname” is the cookie name. If you want to delete more than one cookies try deleteall(), it will delete all the cookies stored in your browser. After applying the delete method I am going to verify whether the cookie is still stored in my browser or deleted. Copy the same check method including the if-else and paste it into the deletecookiebtn function block. After compiling the code again, it will console “The cookie isn’t exist”.

In conclusion, cookie plays a vital role in modern web development. In this article, I have tried to explain the concept in a practical manner. For any clarification write a query in the comment section. Hit clap if you like it.

--

--

Joy Sen

A tech savvy, like to learning and sharing computer programming related knowledge.