Code Monkey home page Code Monkey logo

tiny-cookie's Introduction

tiny-cookie

Node.js CI codecov npm npm

English | 简体中文

A tiny cookie manipulation plugin for browser.

Upgrade from 1.x to 2.x: You can check the CHANGELOG.md

If you're used tiny-cookie, then you may be interest in micell, a collection of functions focusing on web development.

Install

NPM:

npm install tiny-cookie

Usage

ES2015 (recommended)

// You can import all methods.
import * as Cookies from 'tiny-cookie'

// Or, you can import the methods as needed.
import { isEnabled, get, set, remove } from 'tiny-cookie'

// No alias required, just imports.
import { isCookieEnabled, getCookie, setCookie, removeCookie } from 'tiny-cookie'

The tiny-cookie will expose an object Cookie on the global scope. Also, it can be as a CommonJS/AMD module (recommended).

APIs

isEnabled()

Alias: isCookieEnabled

Check if the cookie is enabled.

get(key)

Alias: getCookie

Get the cookie value with decoding, using decodeURIComponent.

getRaw(key)

Alias: getRawCookie

Get the cookie value without decoding.

getAll()

Alias: getAllCookies

Get all cookies with decoding, using decodeURIComponent.

set(key, value, options)

Alias: setCookie

Set a cookie with encoding the value, using encodeURIComponent. The options parameter is an object. And its property can be a valid cookie option, such as path(default: root path /), domain, expires/max-age, samesite or secure (Note: the secure flag will be set if it is an truthy value, such as true, or it will be not set). For example, you can set the expiration:

import { setCookie } from 'tiny-cookie';

const now = new Date;
now.setMonth(now.getMonth() + 1);

setCookie('foo', 'Foo', { expires: now.toGMTString() });

The expires property value can accept a Date object, a parsable date string (parsed by Date.parse()), an integer (unit: day) or a numeric string with a suffix character which specifies the time unit.

Unit suffix Representation
Y One year
M One month
D One day
h One hour
m One minute
s One second

Examples:

import { setCookie } from 'tiny-cookie';
const date = new Date;

date.setDate(date.getDate() + 21);

setCookie('dateObject', 'A date object', { expires: date });
setCookie('dateString', 'A parsable date string', { expires: date.toGMTString() });
setCookie('integer', 'Seven days later', { expires: 7 });
setCookie('stringSuffixY', 'One year later', { expires: '1Y' });
setCookie('stringSuffixM', 'One month later', { expires: '1M' });
setCookie('stringSuffixD', 'One day later', { expires: '1D' });
setCookie('stringSuffixh', 'One hour later', { expires: '1h' });
setCookie('stringSuffixm', 'Ten minutes later', { expires: '10m' });
setCookie('stringSuffixs', 'Thirty seconds later', { expires: '30s' });

setRaw(key, value, options)

Alias: setRawCookie

Set a cookie without encoding.

remove(key, options)

Alias: removeCookie

Remove a cookie on the current domain. If you want to remove the parent domain's cookie, you can use the options parameter, such as remove('cookieName', { domain: 'parentdomain.com' }).

FAQ

  1. How to use JSON as the encoder/decoder?

You can write your cookie get and set methods with JSON support easily:

import { getCookie, setCookie } from 'tiny-cookie';

export const getJSON = (key) => getCookie(key, JSON.parse);
export const setJSON = (key, value, options) => setCookie(key, value, JSON.stringify, options);

License

MIT.

tiny-cookie's People

Contributors

alex1990 avatar armano2 avatar sheepsteak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

tiny-cookie's Issues

Target 3.0

  • The encoder parameter of the set method as the last one.
  • Support arbitrary characters in the cookie name/key.
  • Integrate getJSON and setJSON methods.
  • The get method supports getting multiple cookie values. For example, get(['foo', 'bar']).
  • The set method supports setting multiple cookie pairs. For example, set({ foo: 'Foo', bar: 'Bar' }).
  • Add a demo page with github pages.
  • Support using in server. See https://github.com/jshttp/cookie
  • Add wiki document about cookie.

Is the question mark necessary?

diff --git a/tiny-cookie.js b/tiny-cookie.js
index 69541d5..1cd479b 100644
--- a/tiny-cookie.js
+++ b/tiny-cookie.js
@@ -116,7 +116,7 @@
   Cookie.get = function(key, raw) {
     if (typeof key !== 'string' || !key) return null;
 
-    key = '(?:^|; )' + escapeRe(key) + '(?:=([^;]*?))?(?:;|$)';
+    key = '(?:^|; )' + escapeRe(key) + '(?:=([^;]*))?(?:;|$)';
 
     var reKey = new RegExp(key);
     var res = reKey.exec(document.cookie);

The asterisk already means 0 or N. Can we remove the question mark?

Support clear all cookies

The cookie is path aware. So clearing all cookies is impossible with the set path. Besides, this demand is rarely come across in web applications.

Inconsistency with setCookie

At the moment setCookie takes 4 arguments (only 3 of them are documented though).
encoder is an optional argument but for some reason, it's not the last one. And it results in inconsistency:

setCookie('key', 'value'); // encoder == encodeURIComponent

but

setCookie('key', 'value', { domain: 'some.domain' }); // encoder == null

So, I would suggest to make encoder the last argument and also document it.
I can create a PR.

2.4 version

  • Rewrite in TypeScript
  • Support conditional exports
  • Upgrade development dependencies
  • Change eslint config
  • Use Github Actions instead of Travis CI
  • Rename branch "master" to "main"

UMD build

feature request: would be nice if there was a /dist/tiny-cookie.umd.js builld.

Thanks!
-Ben

Don't use code in `src` folder directly for `module` field in package.json

I notice in package.json, module field is the source code of the project, this means when use a build tools support es6 module (like webpack), the build tools would directly import the source code, which might cause some problems with UglifyJs.
For example, in webpack, when we use a babel loader, we usually exclude the node_modules to improve the build speed, so this means when we import tiny-cookie in webpack, the imported code is still in es6, and UglifyJs doesn't support es6.
My suggestion is we can have another folder(like lib), the code should transpile to es5 but it's in es6 module style.
Sorry for my poor english.

Warning: To load an ES module issue

Since I moved to the latest version 2.4.0 and build the project and try to run it in production mode the site throws this error:
The project is built in SvelteKit.

(node:49975) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. (Use node --trace-warnings ... to show where the warning was created) This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason: /Projects/sveltekit-sk/node_modules/tiny-cookie/dist/tiny-cookie.esm.js:168 export { get, getAll, getAll as getAllCookies, get as getCookie, getRaw, getRaw as getRawCookie, isEnabled as isCookieEnabled, isEnabled, remove, remove as removeCookie, set, set as setCookie, setRaw, setRaw as setRawCookie };

Set path to root when testing if cookies are enabled

When scanning a site which uses tiny-cookie through a service like https://www.onetrust.com/, we see an increased number in the reports of the @key@-cookie.

That's because the @key@-cookie is set to a relative path (eg. /features/foo, /features/bar) instead of a root path /.

function isEnabled() {
const key = '@key@';
const value = '1';
const re = new RegExp(`(?:^|; )${key}=${value}(?:;|$)`);
document.cookie = `${key}=${value}`;
const enabled = re.test(document.cookie);
if (enabled) {
// eslint-disable-next-line
remove(key);
}
return enabled;
}

Would you be open to a change, where the cookie path is updated to root (/)?
The changes would look like this:

- document.cookie = `${key}=${value}`;
+ document.cookie = `${key}=${value}; path=/`;

Can't remove() cookies set on custom domain

I am unable to remove cookies that have been set with a custom domain using the remove function, instead having to call set with a negative expires value.

One solution would be to allow options to be passed to remove.

tinyCookie.set('test', '1', {expires: 180, domain: 'custom.tld'}) // exposes cookie on *.custom.tld
tinyCookie.remove('test') // doesn't remove cookie
tinyCookie.set('test', '1', {expires: -1, domain: 'custom.tld'}) // removes cookie

Modern development flow

  • Use ES2015+.
  • Use npm scripts instead of gulp.
  • Reorganize the directory: src for ES2015+ code, lib for ES5 code, dist for release code.
  • Support CI test with phantomjs or headless chrome.
  • Use mocha test framework.
  • One command to start an HTTPS server.
  • Add cookie related links.

References

Invalid "main" entry in package.json?

"main" in package.json seems to point to lib/tiny-cookie.js, but there is no such file. Is there some reasoning behind this? To get the library to work with browserify, I added the following to my package.json:

  "browser": {
    "tiny-cookie": "tiny-cookie/dist/tiny-cookie.js"
  },

undefined when importing via babel

Importing tiny-cookie via babel appears to return undefined in v2.0.1:
https://gist.github.com/mogelbrod/2b0dc06094fae5ce460889d89bec5c62

babel-node index.js outputs undefined for me using the set up defined in the gist above.

Installed npm modules:

$ npm list --depth 1
[email protected] /Users/victor/src/test-cookie
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
└── [email protected]

Support JSON encoding and decoding

While, in actually, JSON encoding and decoding is used rarely with cookie. At least, I never use it. But we can support it with an abstract transformer. JSON.stringify and encodeURIComponent are both encode transformer, JSON.parse and decodeURIComponent are both decode transformer. So we can make the code concise and extensible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.