Cookie
Simple cookie management.
Demos
Basic
Create, read, and remove cookies. Cookies are no longer support in CodePen embeds, but the following will work in your browser's console. Feel free to play around there.
Cookie.set('foo', 'bar');
Cookie.set('fizz', 'bat');
console.log(Cookie.get('foo')); // bar
console.log(Cookie.get('fizz')); // baz
Cookie.delete('foo');
console.log(Cookie.get('foo')); // null
Options
Set global options by passing a valid object to the public .defaults() method.
| Name | Type | Default | Description |
|---|---|---|---|
domain |
string |
null |
Cookie domain |
expires |
number |
604800000 |
Expiration time in milliseconds (default 7 days) |
path |
string |
null |
Cookie path |
samesite |
string |
'Lax' |
SameSite attribute ('Strict', 'Lax', or 'None') |
secure |
boolean |
null |
Secure attribute (requires HTTPS) |
Methods
Methods are publicly available, unless otherwise stated.
| Name | Description |
|---|---|
.defaults() |
Sets default options for all future cookie operations |
.set() |
Sets a cookie value |
.get() |
Gets a cookie value by key |
.delete() |
Deletes a cookie |
.defaults()
Sets default options for all future cookie operations.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
options |
object (required) |
{} |
Object containing default options |
Examples
Cookie.defaults({
expires: 3600000, // 1 hour
secure: true
});
.set()
Sets a cookie value.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
key |
string (required) |
'' |
Cookie key/name |
value |
string (required) |
'' |
Cookie value |
options |
object (optional) |
{} |
Object containing options |
Examples
// Set a basic cookie
Cookie.set('username', 'john');
// Set a cookie with custom options
Cookie.set('token', 'abc123', {
expires: 3600000, // 1 hour
secure: true,
samesite: 'Strict'
});
.get()
Gets a cookie value by key.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
key |
string (required) |
'' |
Cookie key/name |
Returns
| Type | Description |
|---|---|
string|null |
Cookie value or null if not found |
Examples
let username = Cookie.get('username');
if (username) {
console.log('Welcome back, ' + username);
}
.delete()
Deletes a cookie by setting its expiration to the past.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
key |
string (required) |
'' |
Cookie key/name |
options |
object (optional) |
{} |
Object containing options (domain and path should match the original cookie) |
Examples
Cookie.delete('username');
// Delete cookie with specific domain/path
Cookie.delete('token', {
domain: '.example.com',
path: '/'
});