How to Set and Get Cookies in Angular With Examples?

A cookie in the context of web development is a small piece of data that a web server stores in the user’s web browser for a limited amount of time.

This data is typically stored in the form of key-value pairs and can be used for different purposes such as tracking, authentication, personalization, etc.

Many websites use cookies to store information about a user when they first visit the site and then use that cookie information to enhance the user’s experience during subsequent visits.

In this article, we will step by step learn how we can store and access cookies from the browser’s cookies storage with the help of relevant examples. So, let’s dive right in.

Installing ngx-cookie-service to Implement Cookies

To implement cookies in Angular, you can either go with the regular document.cookie property provided by JavaScript, or you can use a npm package to make your life easier.

I recommend going with any npm package. We will use ngx-cookie-service npm package as it is widely adopted by developers for simplifying cookie management in Angular applications.

So open your terminal in the root directory of your Angular project and run the following command:

npm install ngx-cookie-service --save

OR you can use the yarn add command if you are using yarn:

yarn add ngx-cookie-service

On successful installation, the ngx-cookie-service will be added to the dependencies section of your package.json file:

Check if ngx-cookie-service is installed or not

Using ngx-cookie-service to Set Cookies in Browser

Once the ngx-cookie-service is installed, you are ready to directly use it in your Angular application.

Step 1: Import the CookieService from the ngx-cookie-service package

import { CookieService } from 'ngx-cookie-service';

Step 2: Inject the CookieService dependency into the constructor of your component

constructor(private cookieService: CookieService){}

Step 3: Use the set() method to set the cookie in the browser

this.cookieService.set('cookieName', 'Cookie Value');

Step 4: Use the get() method to get the cookie’s value

const cookieVal = this.cookieService.get('cookieName');

Step 5: Use the delete() method to delete the cookie from the user’s browser

this.cookieService.delete('cookieName');

Here are all the steps put together into one example:

import { Component, OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{

  userCookie: string = '';

  constructor(
    private cookieService: CookieService
  ){}

  ngOnInit(): void { 
    this.userCookie = this.getCookie();
  }

  setCookie(){
    this.cookieService.set('user', "programmersportal.com");
  }

  getCookie(){
    return this.cookieService.get('user');
  }

  deleteCookie(){
    this.cookieService.delete('user');
  }

}

To check if the cookie is stored properly in the browser or not, you can open the developer tools by pressing CTRL + SHIFT + I on the browser and then head over to the Application section.

In the application section there will be a Cookies section, just click on it and you will see all the stored cookies.

Refer to the image below:

How to Check all the Stored Cookies in your Browser

Getting All the Cookies

To get all the cookies, you can use the CookieService.getAll() method. The CookieService.getAll() method returns an object containing all the cookies as key-value pairs.

this.cookieService.getAll();
// Output:
// {user: 'programmersportal.com', token: 'fjk@9043hafha&r3'}

Deleting All the Cookies

To delete all the cookies from the browser at once, call the CookieService.deleteAll() method.

Example:

this.cookieService.deleteAll();

Check if a Cookie Exists in the Browser

To check if a cookie exists in the browser or not, call the CookieService.check() method. If the CookieService.check() method returns true, the cookie exists, otherwise it doesn’t exist.

Example:

this.cookieService.check('cookieName')

All Methods Provided by the ngx-cookie-service

Here are all the methods provided by the ngx-cookie-service package:

  • check(cookieName) – Returns true if the specified cookie exists, else returns false.
  • set(key, value) – Stores a cookie with the specified name in the browser
  • get(key) – Returns the value of the specified cookie.
  • getAll() – Returns an object containing all the cookies.
  • delete(key) – Deletes a cookie with the specified name
  • deleteAll() – Deletes all the cookies

Conclusion

In this article, we learned how we can set, get and delete a cookie in Angular using ngx-cookie-service npm package.

To summarize, we use the CookieService.set() method to set the cookie, the CookieService.get() method to get the cookie and the CookieService.delete() method to delete the cookie from the browser.

I hope you liked this article. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts