npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngx-cookie-service-ssr

v19.0.0

Published

Angular SSR cookie service

Downloads

27,743

Readme

NGX Cookie Service

build ngx-cookie-service channel on discord

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

Installation

npm install ngx-cookie-service --save

# or

yarn 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(private
cookieService: 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 dedicated library 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 not available in SSR because document object is not available. To overcome this, navigate to server.ts file in your SSR project, 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 can use REQUEST.cookies to access the cookies 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 the library. For versions <=12.x.x, use 12.0.3 version

| Angular Version | Supported Version | |------------------------|-------------------| | 19.x.x | 19.x.x | | 18.x.x | 18.x.x | | 17.x.x | 17.x.x | | 16.x.x | 16.x.x | | 15.x.x | 15.x.x | | 14.x.x | 14.x.x | | 13.x.x | 13.x.x | | <=12.x.x (View Engine) | 12.0.3 |

API

check( name: string ): boolean;

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

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

get( name: string ): string;

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 the path value, use '/'. If no path or domain is explicitly defined, the current location is assumed. sameSite defaults to Lax.

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

Important: 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'.

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 the path 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 StackOverflow answer 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 about the path value, use '/'.

FAQ

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 in general:

I am always getting a "token missing" or "no provider" error.

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

rm -rf node_modules
yarn # 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 or Springboot application for you. In that case, you are better off asking the nice folks over at StackOverflow for help.

Do you support Angular Universal?

There is an issue for that. Check out this comment for more information about future support.

Opening issues

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

Contributing

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 to add them, of course).

Author

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

Contributors

Thanks to all contributors:

License

MIT