0
# JS Cookie
1
2
JS Cookie is a simple, lightweight JavaScript API for handling browser cookies. It provides a clean interface for creating, reading, and deleting cookies with support for various attributes and encoding options. The library works in all browsers, has no dependencies, supports JSON data, and is RFC 6265 compliant.
3
4
## Package Information
5
6
- **Package Name**: js-cookie
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install js-cookie`
10
11
## Core Imports
12
13
ESM (recommended for modern bundlers):
14
15
```javascript
16
import Cookies from "js-cookie";
17
```
18
19
For CommonJS:
20
21
```javascript
22
const Cookies = require("js-cookie");
23
```
24
25
For AMD:
26
27
```javascript
28
define(["js-cookie"], function(Cookies) {
29
// Use Cookies
30
});
31
```
32
33
For browser (global):
34
35
```javascript
36
// Available as window.Cookies
37
// Use Cookies.noConflict() to avoid namespace conflicts if needed
38
// Note: noConflict() only available in browser environment
39
```
40
41
## Basic Usage
42
43
```javascript
44
// Using ESM import or const Cookies = require("js-cookie") for CommonJS
45
46
// Set a simple cookie
47
Cookies.set("name", "value");
48
49
// Set a cookie with expiration (7 days from now)
50
Cookies.set("user", "john", { expires: 7 });
51
52
// Set a cookie with custom attributes
53
Cookies.set("token", "abc123", {
54
expires: 1,
55
path: "/admin",
56
domain: ".example.com",
57
secure: true
58
});
59
60
// Read a cookie
61
const name = Cookies.get("name"); // "value"
62
const missing = Cookies.get("missing"); // undefined
63
64
// Read all cookies
65
const allCookies = Cookies.get(); // { name: "value", user: "john", ... }
66
67
// Remove a cookie
68
Cookies.remove("name");
69
70
// Remove a cookie with specific attributes (must match set attributes)
71
Cookies.remove("token", { path: "/admin", domain: ".example.com" });
72
```
73
74
## Capabilities
75
76
### Cookie Creation
77
78
Creates or updates a cookie with optional attributes.
79
80
```javascript { .api }
81
/**
82
* Creates or updates a cookie
83
* @param {string} key - Cookie name
84
* @param {string|object|array} value - Cookie value (objects/arrays are JSON stringified)
85
* @param {object} [attributes] - Cookie attributes
86
* @returns {string} The cookie string that was set
87
*/
88
Cookies.set(key, value, attributes);
89
```
90
91
### Cookie Reading
92
93
Reads cookie values, optionally parsing JSON data.
94
95
```javascript { .api }
96
/**
97
* Reads a cookie value as raw string
98
* @param {string} [key] - Cookie name. If omitted, returns all cookies
99
* @returns {string|undefined|object} Single value, undefined, or all cookies object
100
*/
101
Cookies.get(key);
102
103
/**
104
* Reads a cookie value and parses it as JSON
105
* @param {string} [key] - Cookie name. If omitted, returns all cookies parsed as JSON
106
* @returns {any|undefined|object} Parsed JSON value, undefined, or all cookies parsed
107
*/
108
Cookies.getJSON(key);
109
```
110
111
### Cookie Deletion
112
113
Removes cookies from the browser.
114
115
```javascript { .api }
116
/**
117
* Deletes a cookie by setting it to expire in the past
118
* @param {string} key - Cookie name to delete
119
* @param {object} [attributes] - Must match the path and domain used when setting
120
* @returns {undefined}
121
*/
122
Cookies.remove(key, attributes);
123
```
124
125
### Configuration
126
127
Global default attributes and namespace management.
128
129
```javascript { .api }
130
/**
131
* Default attributes applied to all cookie operations
132
* @type {object}
133
*/
134
Cookies.defaults;
135
136
/**
137
* Restores original window.Cookies and returns js-cookie API
138
* BROWSER ONLY: Not available in AMD/CommonJS environments
139
* @returns {object} Cookies API object with all cookie methods
140
*/
141
Cookies.noConflict();
142
```
143
144
### Custom Converters
145
146
Creates new Cookies instances with custom encoding/decoding.
147
148
```javascript { .api }
149
/**
150
* Creates a new Cookies instance with custom encoding/decoding
151
* @param {function|object} converter - Function for read-only conversion, or object with read/write methods
152
* @returns {object} New Cookies API instance with custom converter applied
153
*/
154
Cookies.withConverter(converter);
155
```
156
157
## Cookie Attributes
158
159
The following attributes can be passed to `Cookies.set()` or set in `Cookies.defaults`:
160
161
### expires
162
- **Type**: `number | Date`
163
- **Description**: Cookie expiration (Number = days from now, Date = specific date)
164
- **Default**: Session cookie (expires when browser closes)
165
166
### path
167
- **Type**: `string`
168
- **Description**: Cookie path scope
169
- **Default**: `"/"`
170
171
### domain
172
- **Type**: `string`
173
- **Description**: Cookie domain scope
174
- **Default**: Current domain
175
176
### secure
177
- **Type**: `boolean`
178
- **Description**: Cookie only sent over HTTPS
179
- **Default**: `false`
180
181
## JSON Support
182
183
JS Cookie provides automatic JSON handling for objects and arrays:
184
185
```javascript
186
// Setting objects/arrays - automatically JSON.stringify'd
187
Cookies.set("user", { name: "John", age: 30 });
188
Cookies.set("items", ["apple", "banana", "cherry"]);
189
190
// Reading as raw string
191
Cookies.get("user"); // '{"name":"John","age":30}'
192
193
// Reading as parsed JSON
194
Cookies.getJSON("user"); // { name: "John", age: 30 }
195
Cookies.getJSON("items"); // ["apple", "banana", "cherry"]
196
197
// Reading all cookies as JSON
198
Cookies.getJSON(); // { user: { name: "John", age: 30 }, items: [...] }
199
```
200
201
## Custom Encoding/Decoding
202
203
Create custom Cookies instances for special encoding needs:
204
205
```javascript
206
// Custom read converter
207
const customCookies = Cookies.withConverter(function (value, name) {
208
if (name === "special") {
209
return unescape(value);
210
}
211
// Default decoding for other cookies
212
});
213
214
// Custom read/write converters
215
const encodedCookies = Cookies.withConverter({
216
read: function (value, name) {
217
// Custom read logic
218
return decodeSpecialFormat(value);
219
},
220
write: function (value, name) {
221
// Custom write logic
222
return encodeSpecialFormat(value);
223
}
224
});
225
226
customCookies.get("special"); // Uses custom decoder
227
encodedCookies.set("data", "value"); // Uses custom encoder
228
```
229
230
## Advanced Examples
231
232
```javascript
233
// Set default attributes for all cookies
234
Cookies.defaults = {
235
expires: 7,
236
path: "/",
237
secure: true
238
};
239
240
// All subsequent cookies will use these defaults
241
Cookies.set("session", "abc123"); // Will expire in 7 days, be secure
242
243
// Override defaults for specific cookies
244
Cookies.set("temp", "data", { expires: 1 }); // Expires in 1 day instead of 7
245
246
// Namespace conflict resolution (browser only)
247
const myCookies = Cookies.noConflict();
248
// Original window.Cookies is restored
249
// Use myCookies for js-cookie functionality
250
251
// Complex cookie with all attributes
252
Cookies.set("complex", { user: "admin", role: "superuser" }, {
253
expires: new Date("2024-12-31"),
254
path: "/admin",
255
domain: ".mysite.com",
256
secure: true
257
});
258
259
// Read and validate
260
const complexData = Cookies.getJSON("complex");
261
if (complexData && complexData.role === "superuser") {
262
// Handle admin user
263
}
264
```