ngx-cookie-service (2024)

ngx-cookie-service (1)ngx-cookie-service (2)ngx-cookie-service (3)ngx-cookie-service (4)

Angular service to read, set and delete browser cookies. Originally based onthe ng2-cookies library. The experienced teambehind Studytube will take care of our cookie service from now on.

Installation

npm install ngx-cookie-service --save# oryarn add ngx-cookie-service

Usage

Add the cookie service to your app.module.ts as a provider:

import {CookieService} from 'ngx-cookie-service';@NgModule({ ... providers:[CookieService],...})export class AppModule {}

Then, import and inject it into a constructor:

constructor(privatecookieService: CookieService){ this.cookieService.set('Test', 'Hello World'); this.cookieValue = this.cookieService.get('Test');}

That's it!

Angular 14+

  1. Angular 14 introduced support for standalone components.If you are using just standalone components, you can import the service directly into the component

    import { CookieService } from 'ngx-cookie-service';import { Component } from '@angular/core';@Component({ selector: 'my-component', template: `<h1>Hello World</h1>`, providers: [CookieService],})export class HelloComponent { constructor(private cookieService: CookieService) { this.cookieService.set('Test', 'Hello World'); this.cookieValue = this.cookieService.get('Test'); }}
  2. You can also use inject() method in v14+ to inject the service into the component

    import { CookieService } from 'ngx-cookie-service';import { Component, inject } from '@angular/core';@Component({ selector: 'my-component', template: `<h1>Hello World</h1>`, providers: [CookieService],})export class HelloComponent { cookieService = inject(CookieService); constructor() { this.cookieService.set('Test', 'Hello World'); this.cookieValue = this.cookieService.get('Test'); }}

Server Side Rendering

Ngx Cookie Service supports Server Side Rendering (SSR) via dedicatedlibrary ngx-cookie-service-ssr.Only install ngx-cookie-service-ssr library (and skip ngx-cookie-service) for SSR

  1. Install the library using below command

     npm install ngx-cookie-service-ssr --save # or yarn add ngx-cookie-service-ssr
  2. By default, browser cookies are notavailable in SSR because document object is not available. To overcome this, navigate to server.ts file in yourSSRproject, and replace the following code

    server.get('*', (req, res) => { res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });});

with this

server.get('*', (req, res) => { res.render(indexHtml, { req, providers: [ { provide: APP_BASE_HREF, useValue: req.baseUrl }, { provide: 'REQUEST', useValue: req }, { provide: 'RESPONSE', useValue: res }, ], });});
  1. This will make sure the cookies are available in REQUEST object, and the ngx-cookie-service-ssr canuse REQUEST.cookies to access thecookies in SSR. Then proceed to use ngx-cookie-service as usual.
  2. See the sample repo for more details.

Demo

https://stackblitz.com/edit/angular-ivy-1lrgdt?file=src%2Fapp%2Fapp.component.ts

Supported Versions

ViewEngine support has been removed on 13.x.x. For Angular versions 13.x.x or later use the latest version of thelibrary. For versions <=12.x.x, use 12.0.3 version

Angular VersionSupported Version
16.x.x16.x.x
15.x.x15.x.x
14.x.x14.x.x
13.x.x13.x.x
<=12.x.x (View Engine)12.0.3

check( name: string ): boolean;

const cookieExists: boolean = cookieService.check('test');

Checks if a cookie with the givenname can be accessed or found.

const value: string = cookieService.get('test');

Gets the value of the cookie with the specified name.

getAll(): {};

const allCookies: {} = cookieService.getAll();

Returns a map of key-value pairs for cookies that can be accessed.

set( name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'Strict' | 'None' ): void;

set( name: string, value: string, options?: { expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict'}): void;

cookieService.set('test', 'Hello World');cookieService.set('test', 'Hello World', { expires: 2, sameSite: 'Lax' });

Sets a cookie with the specified name and value. It is good practice to specify a path. If you are unsure about thepath value, use '/'. If no path or domain is explicitly defined, the current location is assumed. sameSite defaultsto Lax.

Important: For security reasons, it is not possible to define cookies for other domains. Browsers do not allow this.Read this and this StackOverflowanswer for a more in-depth explanation.

Important: Browsers do not accept cookies flagged sameSite = 'None' if secure flag isn't set as well. CookieServicewill override the secure flag to true if sameSite='None'.

delete( name: string, path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax'): void;

cookieService.delete('test');

Deletes a cookie with the specified name. It is best practice to always define a path. If you are unsure about thepath value, use '/'.

Important: For security reasons, it is not possible to delete cookies for other domains. Browsers do not allow this.Read this and this StackOverflowanswer for a more in-depth explanation.

deleteAll( path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax' ): void;

cookieService.deleteAll();

Deletes all cookies that can currently be accessed. It is best practice to always define a path. If you are unsure aboutthe path value, use '/'.

General tips

Checking out the following resources usually solves most of the problems people seem to have with this cookie service:

The following general steps are usually very helpful when debugging problems with this cookie service or cookies ingeneral:

Package managers are a well known source of frustration. If you have "token missing" or "no provider" errors, a simplere-installation of your node modules might suffice:

rm -rf node_modulesyarn # or `npm install`

I have a problem with framework X or library Y. What can I do?

Please be aware that we cannot help you with problems that are out of scope. For example, we cannot debug a Symfony orSpringboot application for you. In that case, you are better off asking the nice folks overat StackOverflow for help.

Do you support Angular Universal?

There is an issue for that. Checkout this comment for more informationabout future support.

Please make sure to check out our FAQ before you open a new issue. Also, try to give us as much information as you canwhen you open an issue. Maybe you can even supply a test environment or test cases, if necessary?

We are happy to accept pull requests or test cases for things that do not work. Feel free to submit one of those.

However, we will only accept pull requests that pass all tests and include some new ones (as long as it makes sense toadd them, of course).

This cookie service is brought to you by 7leads GmbH. We built it for one of our apps, becausethe other cookie packages we found were either not designed "the Angular way" or caused trouble during AOT compilation.

Thanks to all contributors:

MIT

ngx-cookie-service (2024)
Top Articles
Performance Best Practices Using Express in Production
Understanding Inheritance Taxes: Key Rules for Beneficiaries
Spectrum Gdvr-2007
Froedtert Billing Phone Number
Citibank Branch Locations In Orlando Florida
Uihc Family Medicine
Co Parts Mn
Mawal Gameroom Download
Max 80 Orl
Pwc Transparency Report
104 Presidential Ct Lafayette La 70503
Craigslist Heavy Equipment Knoxville Tennessee
“In my day, you were butch or you were femme”
Sand Castle Parents Guide
Non Sequitur
DoorDash, Inc. (DASH) Stock Price, Quote & News - Stock Analysis
Costco Gas Foster City
10-Day Weather Forecast for Santa Cruz, CA - The Weather Channel | weather.com
Spoilers: Impact 1000 Taping Results For 9/14/2023 - PWMania - Wrestling News
NBA 2k23 MyTEAM guide: Every Trophy Case Agenda for all 30 teams
Sprinkler Lv2
Winco Employee Handbook 2022
Gas Buddy Prices Near Me Zip Code
Crossword Help - Find Missing Letters & Solve Clues
Kroger Feed Login
Cona Physical Therapy
Cfv Mychart
Wheeling Matinee Results
Kaiser Infozone
Rvtrader Com Florida
Matlab Kruskal Wallis
Ma Scratch Tickets Codes
Selfservice Bright Lending
Ludvigsen Mortuary Fremont Nebraska
Lyca Shop Near Me
The Transformation Of Vanessa Ray From Childhood To Blue Bloods - Looper
Td Ameritrade Learning Center
Frommer's Philadelphia &amp; the Amish Country (2007) (Frommer's Complete) - PDF Free Download
Craigslist En Brownsville Texas
Scarlet Maiden F95Zone
RECAP: Resilient Football rallies to claim rollercoaster 24-21 victory over Clarion - Shippensburg University Athletics
Actor and beloved baritone James Earl Jones dies at 93
The Wait Odotus 2021 Watch Online Free
Pink Runtz Strain, The Ultimate Guide
Theater X Orange Heights Florida
3367164101
Cara Corcione Obituary
Erespassrider Ual
4Chan Zelda Totk
Minecraft Enchantment Calculator - calculattor.com
Cheryl Mchenry Retirement
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 6500

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.