Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to set and get cookies in angular

How to set and get cookies in angular ?

Aman Jain, April 14, 2022November 6, 2023

This article will give you the understanding of set and get cookies in angular. Cookies are used to store the data in client computer, Cookie can hold tiny information in computer and can retrieve when required for same website.

Cookies can store key value in client system and its send back the cookies with every request so server can identify the user or session.

this post set and get cookies in angular will work with all version of angular including angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14.

Why cookies are useful ?

Cookies are very useful for every website because without cookies server will unable to maintain the session for a request response. For example when we make a request to a website server, server sent response to user and the close the connection so here for next request server doesn’t know about the request is from same browser or client or it’s from different client. Therefore here cookies play the role to send some information by which server can identify it’s from same browser.

If you look at server side languages each language creates its own cookie to create the session as below

Screenshot 2022 04 14 at 8.18.44 AM
Cookies

In this tutorial we will learn to create cookies by two methods

  1. Using native javascript way
  2. Using the third party package of angular

So let’s start set and get cookies in angular in native javascript

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 2: Create a service

Create a service so we can use it across the components

ng g s Cookie 

this will create a file as below in app directory and add the service in app module

Here is the code for Cookie service

import { Injectable } from '@angular/core';

@Injectable()
export class CookieService {
  constructor() {}

  public getCookie(name: string) {
    let ca: Array<string> = document.cookie.split(';');
    console.log(document.cookie);
    let caLen: number = ca.length;
    let cookieName = `${name}=`;
    let c: string;

    for (let i: number = 0; i < caLen; i += 1) {
      c = ca[i].replace(/^\s+/g, '');
      if (c.indexOf(cookieName) == 0) {
        return c.substring(cookieName.length, c.length);
      }
    }
    return '';
  }

  public deleteCookie(cookieName) {
    this.setCookie({ name: cookieName, value: '', expireDays: -1 });
  }

  /**
   * Expires default 1 day
   * If params.session is set and true expires is not added
   * If params.path is not set or value is not greater than 0 its default value will be root "/"
   * Secure flag can be activated only with https implemented
   * Examples of usage:
   * {service instance}.setCookie({name:'token',value:'abcd12345', session:true }); <- This cookie will not expire
   * {service instance}.setCookie({name:'userName',value:'John Doe', secure:true }); <- If page is not https then secure will not apply
   * {service instance}.setCookie({name:'niceCar', value:'red', expireDays:10 }); <- For all this examples if path is not provided default will be root
   */
  public setCookie(params: any) {
    let d: Date = new Date();
    d.setTime(
      d.getTime() +
        (params.expireDays ? params.expireDays : 1) * 24 * 60 * 60 * 1000
    );
    document.cookie =
      (params.name ? params.name : '') +
      '=' +
      (params.value ? params.value : '') +
      ';' +
      (params.session && params.session == true
        ? ''
        : 'expires=' + d.toUTCString() + ';') +
      'path=' +
      (params.path && params.path.length > 0 ? params.path : '/') +
      ';' +
      (location.protocol === 'https:' && params.secure && params.secure == true
        ? 'secure'
        : '');
  }
}

Step 3: Add components and inject service

Now, create two components one for set the cookie and other for get the cookie in different pages

ng g c SetCookieExample

This will create a folder in app directory named with set-cookie-example and here is component file

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

@Component({
  selector: 'app-set-cookie-example',
  templateUrl: './set-cookie-example.component.html',
  styleUrls: ['./set-cookie-example.component.css'],
})
export class SetCookieExampleComponent implements OnInit {
  constructor(public cookie: CookieService) {}

  ngOnInit() {
    this.cookie.setCookie({
      name: 'user',
      value: 'Readerstack',
      session: true,
    });
  }
}

here we injected the Cookie service and then set user cookie in browser

this.cookie.setCookie({
      name: 'user',
      value: 'Readerstack',
      session: true,
    });

Html to link to another page

<p>We have set cookies on this page</p>
<a routerLink="get-cookie">Get cookie another page</a>

Create another component to get the cookies

ng g c GetCookieExample

This will create a folder in app directory named with get-cookie-example and here is component file

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

@Component({
  selector: 'app-get-cookie-example',
  templateUrl: './get-cookie-example.component.html',
  styleUrls: ['./get-cookie-example.component.css'],
})
export class GetCookieExampleComponent implements OnInit {
  user: string;

  constructor(public cookie: CookieService) {}

  ngOnInit() {
    this.user = this.cookie.getCookie('user');
  }
}

we fetched the stored value in cookie using this.user = this.cookie.getCookie('user');

Html to display name

<p>Getting cookie on this page</p>
User : {{ user }}

Step 4: Add routes in app routing

Finally add the routes in app.routing.module.ts to test the implementation

import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SetCookieExampleComponent } from './set-cookie-example/set-cookie-example.component';
import { GetCookieExampleComponent } from './get-cookie-example/get-cookie-example.component';
import { CookieService } from './cookie.service';

@NgModule({
  declarations: [SetCookieExampleComponent, GetCookieExampleComponent],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      { path: '', component: SetCookieExampleComponent },
      { path: 'get-cookie', component: GetCookieExampleComponent },
    ]),
  ],
  exports: [RouterModule],
  providers: [CookieService],
})
export class AppRoutingModule {}

Also note here we added the Service in app.module.ts file

... 
providers: [CookieService]
....

Run the application and check implementation

Live Demo https://set-and-get-cookies-in-angular-readerstacks.stackblitz.io/

Download Code : https://stackblitz.com/edit/set-and-get-cookies-in-angular-readerstacks

beenhere

Also Read:

How to set and get cookies in angular using package ?

Related

Javascript Angular angularcookie

Post navigation

Previous post
Next post

Related Posts

Javascript How to get query string params in angular 12

How to get query string params in angular 12 ?

April 6, 2022October 4, 2022

In this tutorial i will show you to get the query string params in angular using ActivatedRoute. Angular completely works in different way from other javascript frameworks, Angular uses its own routing framework to land between the pages. Let’s quickly deep dive in to the topic and learn it. So…

Read More
Javascript Setup Client side javascript validation

How to Setup Client side javascript validation ?

September 16, 2021September 29, 2021

In this tutorial we will learn javascript validation without using any third party library. we will validate the simple form with 5 inputs fields. Let’s start with simple steps Step 1: Create a html file Firstly we are going to create html file which contains a form with basic fields….

Read More

How to check jQuery checkbox checked or not ?

January 25, 2022January 25, 2022

In this article i will show you multiple way to check or validate if a checkbox is checked or not. Also i will show you to check a checkbox programmatically. In the post we will learn all possibilities to validate a checkbox and how we can check a checkbox using…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version