How to Set Angular 4+ Cookie Service Expiry Date in Hours, Minutes, Days and Custom Date

Updated on: May 27, 2021

Every Web application uses Browser Cookies to store logged In User data or application related data, In Angular also we can use the Cookies and set expiry to those cookies so that after the expiry the cookies will be deleted automatically from the browser, know how to set expiry to Angular Cookie Service used in your Angular 4,6,8 + Applications

  • You can use "Cookies Services" package in Angular application to store data into Browser Cookies.
  • Refer article to know, how to install package and its steps to use: Install & Use Angular 4+ Cookies Services 
  • The browser cookies of the website will get deleted when you delete the entire history of the browser along with the stored cookies.
  • When you don't set expiry date to cookies while setting cookies using "set" method, it will get expire when the browsing session ends, it means when you close all the open tabs of the browser, then it will end the session.

1. Set Expiry to Cookies by Minutes:

const dateNow = new Date();
dateNow.setMinutes(dateNow.getMinutes() + 10);
this.cookieService.set('isLoggedIn', 'true', dateNow);

You can see from the below screenshot, that we have run the Angular application in Chrome Browser and it stored cookies along with created date and expiry date of the cookies. We have set expiry date of this cookie to 10 minutes from the created time.

2. Set Expiry to Cookies by Hours:

const dateNow = new Date();
dateNow.setHours(dateNow.getHours() + 2);
this.cookieService.set('isLoggedIn', 'true', dateNow);

You can see from the below screenshot, we have set expiry date of this cookie to 2 hours from the created time.

3. Set Expiry to Cookies by Days:

const dateNow = new Date();
dateNow.setDate(dateNow.getDate() + 15);
this.cookieService.set('isLoggedIn', 'true', dateNow);

You can see from the below screenshot, we have set expiry date of this cookie to 15 days from the created time.

3. Set Expiry to Cookies by Custom Date:

const dateNow = new Date(2020, 1, 25, 13, 30, 30);
this.cookieService.set('isLoggedIn', 'true', dateNow);

You can see from the below screenshot, we have set expiry date of this cookie to custom date which is 25th February 2020 at 1:30:30 pm. So when this computer timing crosses this expiry date, then this cookies will get deleted automatically.