UNPKG

7.01 kBMarkdownView Raw
1# ngx-cookie [![CI](https://github.com/salemdar/ngx-cookie/workflows/CI/badge.svg)](https://github.com/salemdar/ngx-cookie/actions?query=workflow%3ACI) [![npm version](https://img.shields.io/npm/v/ngx-cookie.svg)](https://www.npmjs.com/package/ngx-cookie) [![Downloads](http://img.shields.io/npm/dm/ngx-cookie.svg)](https://npmjs.org/package/ngx-cookie)
2
3
4> Implementation of Angular 1.x $cookies service to Angular
5
6## Table of contents:
7- [Get Started](#get-started)
8 - [Installation](#installation)
9 - [Usage](#usage)
10 - [Server Side Rendering](#ssr)
11 - [Examples](#examples)
12- [CookieService](#cookieservice)
13 - [get()](#get)
14 - [getObject()](#getobject)
15 - [getAll()](#getall)
16 - [put()](#put)
17 - [putObject()](#putobject)
18 - [remove()](#remove)
19 - [removeAll()](#removeall)
20- [Options](#options)
21
22## <a name="get-started"></a> Get Started
23
24### <a name="installation"></a> Installation
25
26You can install this package locally with npm.
27
28```bash
29# To get the latest stable version and update package.json file:
30yarn add ngx-cookie
31# or
32# npm install ngx-cookie --save
33```
34
35### <a name="usage"></a> Usage
36
37`CookieModule` should be registered in angular module with `withOptions()` static method.
38These methods accept `CookieOptions` objects as well. Leave it blank for the defaults.
39
40```typescript
41import { NgModule } from '@angular/core';
42import { BrowserModule } from '@angular/platform-browser';
43
44import { CookieModule } from 'ngx-cookie';
45
46import { AppComponent } from './app.component';
47
48@NgModule({
49 imports: [ BrowserModule, CookieModule.withOptions() ],
50 declarations: [ AppComponent ],
51 bootstrap: [ AppComponent ]
52})
53export class AppModule { }
54```
55
56```typescript
57import { Component } from '@angular/core';
58import { CookieService } from 'ngx-cookie';
59
60@Component({
61 selector: 'my-very-cool-app',
62 template: '<h1>My Angular App with Cookies</h1>'
63})
64
65export class AppComponent {
66 constructor(private cookieService: CookieService){}
67
68 getCookie(key: string){
69 return this.cookieService.get(key);
70 }
71}
72```
73
74### <a name="ssr"></a> Server Side Rendering
75
76`ngx-cookie` supports usage during Server Side Rendering (SSR / Angular Universal). Getting Server Side Rendering itself set up the first time can be tricky and is outside the scope of this guide. Here, we'll assume that you've got a working SSR setup similar to the [Angular Universal Starter project](https://github.com/angular/universal-starter), and you're just trying to get `ngx-cookie` working with SSR.
77
78Note: during normal, client side usage, `ngx-cookie` manipulates the client cookies attached to the `document` object. During SSR, `ngx-cookie` will manipulate cookies in http request or response headers._
79
80#### Setup
81
82Install `ngx-cookie-backend` library:
83```shell script
84yarn add ngx-cookie-backend
85# or
86# npm install ngx-cookie-backend --save
87```
88
89Then edit `app.server.module.ts` and add `CookieBackendModule.withOptions()` to imports:
90
91```typescript
92/* app.server.module.ts */
93
94import { CookieBackendModule } from 'ngx-cookie';
95
96@NgModule({
97 imports: [
98 AppModule,
99 ServerModule,
100 CookieBackendModule.withOptions()
101 ],
102 bootstrap: [AppComponent]
103})
104export class AppServerModule {}
105```
106Next, we need to make providers for the `'REQUEST'` and `'RESPONSE'` objects created by the expressjs server during SSR. To do this, edit `server.ts` to create providers for `'REQUEST'` AND `'RESPONSE'`.
107
108```typescript
109/* server.ts */
110// All regular routes use the Universal engine
111server.get('*', (req, res) => {
112 res.render(indexHtml, {
113 req,
114 res,
115 providers: [
116 {provide: APP_BASE_HREF, useValue: req.baseUrl},
117 {provide: REQUEST, useValue: req},
118 {provide: RESPONSE, useValue: res}
119 ]
120 });
121});
122```
123
124And that's it! all your application's calls to `CookieService` should now work properly during SSR!
125
126### <a name="examples"></a> Examples
127
128Normal usage example is under `projects/test-app`
129
130SSR usage example is under `projects/backend-test-app`
131
132
133## <a name="cookieservice"></a> CookieService
134
135There are 7 methods available in the `CookieService` (6 standard methods from **Angular 1** and 1 extra `removeAll()` method for convenience)
136
137### <a name="get"></a> get()
138Returns the value of given cookie key.
139
140```typescript
141/**
142 * @param {string} key Id to use for lookup.
143 * @returns {string} Raw cookie value.
144 */
145get(key: string): string;
146```
147
148### <a name="getobject"></a> getObject()
149Returns the deserialized value of given cookie key.
150
151```typescript
152/**
153 * @param {string} key Id to use for lookup.
154 * @returns {Object} Deserialized cookie value.
155 */
156getObject(key: string): Object;
157```
158
159### <a name="getall"></a> getAll()
160Returns a key value object with all the cookies.
161
162```typescript
163/**
164 * @returns {Object} All cookies
165 */
166getAll(): any;
167```
168
169### <a name="put"></a> put()
170Sets a value for given cookie key.
171
172```typescript
173/**
174 * @param {string} key Id for the `value`.
175 * @param {string} value Raw value to be stored.
176 * @param {CookieOptions} options (Optional) Options object.
177 */
178put(key: string, value: string, options?: CookieOptions): void;
179```
180
181### <a name="putobject"></a> putObject()
182Serializes and sets a value for given cookie key.
183
184```typescript
185/**
186 * @param {string} key Id for the `value`.
187 * @param {Object} value Value to be stored.
188 * @param {CookieOptions} options (Optional) Options object.
189 */
190putObject(key: string, value: Object, options?: CookieOptions): void;
191```
192
193### <a name="remove"></a> remove()
194Remove given cookie.
195
196```typescript
197/**
198 * @param {string} key Id of the key-value pair to delete.
199 * @param {CookieOptions} options (Optional) Options object.
200 */
201remove(key: string, options?: CookieOptions): void;
202```
203
204### <a name="removeall"></a> removeAll()
205Remove all cookies.
206
207```typescript
208/**
209 */
210removeAll(): void;
211```
212
213## <a name="options"></a> Options
214
215Options object should be a type of `CookieOptions` interface. The object may have following properties:
216
217- **path** - {string} - The cookie will be available only for this path and its sub-paths. By default, this is the URL that appears in your `<base>` tag.
218- **domain** - {string} - The cookie will be available only for this domain and its sub-domains. For security reasons the user agent will not accept the cookie if the current domain is not a sub-domain of this domain or equal to it.
219- **expires** - {string|Date} - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" or a Date object indicating the exact date/time this cookie will expire.
220- **secure** - {boolean} - If `true`, then the cookie will only be available through a secured connection.
221- **sameSite** - {"Lax"|"Strict"|"None"} - Designates cookie for first party (Lax|Strict) or third party contexts.
222- **httpOnly** - {boolean} - If `true`, then the cookie will be set with the `HttpOnly` flag, and will only be accessible from the remote server. Helps to prevent against XSS attacks.
223- **storeUnencoded** - {boolean} - If `true`, then the cookie value will not be encoded and will be stored as provided.