1.0.0-rc.1 • Published 4 years ago

ngu-cookies v1.0.0-rc.1

Weekly downloads
8
License
MIT
Repository
github
Last release
4 years ago

Node.js CI Conventional Commits License: MIT codecov Quality Gate Status

NguCookies

This is an angular library which provides complete access to cookies in angular universal apps.

Getting started

Installation

npm install ngu-cookies --save
# or
yarn add ngu-cookies

Usage

BrowserModule

The NguCookiesModule should be imported in your bootstrapped module (i.e. AppModule) like this:

import { NgModule } from '@anular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NguCookiesModule } from 'ngu-cookies';

import { AppComponent } from './app.component';

@NgModule({
  imports: [BrowserModule, NguCookiesModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppMocule {}

It is possible to configure some defaults for writing cookies like this:

import { NgModule } from '@anular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NguCookiesModule } from 'ngu-cookies';

import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    NguCookiesModule.withConfig({
      domain: '.example.com',
      path: '/'
      sameSite: 'strict',
      secure: true,
      maxAge: 10,
      expires: new Date(),
      skipUriEncoding: true,
    }),
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ],
})
export class AppMocule {}

ServerModule

To use this library in angular universal you need to add the NguCookiesBackendModule to your module definition for the server (i.e. app.server.module.ts) like this:

import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { NguCookiesBackendModule } from 'ngu-cookies';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [AppModule, ServerModule, NguCookiesBackendModule],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

and you must make sure both req and res are passed to .render() in your server (i.e. server.ts) method like this:

server.get('*', (req, res) => {
  res.render(indexHtml, {
    req,
    res, // <-- this is missing in autogenerated server.ts
    providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
  });
});

CookiesService

To access cookies you can Inject the CookiesService into your Component, Directive, Service, etc like this

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

import { CookiesService } from 'ngu-cookies';

@Injectable()
export class SomeService {
  constructor(private cookies: CookiesService) {}

  readUserCookie(): string {
    return this.cookies.get('user');
  }
}