Isomorphic Cookies
Isomorphic bulletproof cookie functions for Client and Server.
- π· 100% Tests coverage;
- π¦ No external dependencies, no
underscore
, nojQuery
, noBlaze
; - π₯ Works on both Server and Client;
- γοΈ With Unicode support for cookies' value;
- π¨βπ» With
String
,Array
,Object
, andBoolean
support as cookies' value; - βΏ IE support, thanks to @derwok;
- π¦ Looking for Client's (Browser) persistent storage? Try
ClientStorage
package.
Install:
meteor add ostrio:cookies
ES6 Import:
import { Cookies } from 'meteor/ostrio:cookies';
API:
Note: On a server, cookies will be set only after headers are sent (on next route or page reload). To send cookies from Client to Server without a page reload use send()
method.
Server Usage Note: On a server Cookies implemented as a middleware. To get access to current user's cookies use req.Cookies
instance. For more - see examples section below.
new Cookies(opts)
[Isomorphic]
Fetch cookies Create new instance of Cookies
opts.auto
{Boolean} - [Server] Auto-bind in middleware asreq.Cookies
, by defaulttrue
opts.handler
{Function} - [Server] Middleware function with one argumentcookies
asCookies
instance. See "Alternate Usage" sectionopts.TTL
{Number} - Default cookies expiration time (max-age) in milliseconds, by default -session
(no TTL)opts.runOnServer
{Boolean} - Set tofalse
to avoid server usage (by default -true
)
import { Cookies } from 'meteor/ostrio:cookies';
const cookies = new Cookies();
cookies.get(key)
[Isomorphic]
Read a cookie. If the cookie doesn't exist a null
will be returned.
key
{String} - The name of the cookie to read
cookies.set(key, value, [opts])
[Isomorphic]
Create/overwrite a cookie.
key
{String} - The name of the cookie to create/overwritevalue
{String|Number|Boolean|Object|Array} - The value of the cookieopts
{Object} - [Optional]opts.expires
{Number|Date|Infinity} - [Optional] Date, Number as milliseconds or Infinity for a never-expires cookie. If not specified the cookie will expire at the end of session (number as milliseconds or Date object)opts.maxAge
{Number} - [Optional] The max-age in seconds (e.g.31536e3
for a year)opts.path
{String} - [Optional] The path from where the cookie will be readable. E.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, see: docsopts.domain
{String} - [Optional] The domain from where the cookie will be readable. E.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not specified, defaults to the host portion of the current document location (string or null)opts.secure
{Boolean} - [Optional] The cookie will be transmitted only over secure protocol ashttps
opts.httpOnly
{Boolean} - [Optional] An HttpOnly cookie cannot be accessed by client-side APIs, such as JavaScript. This restriction eliminates the threat of cookie theft via cross-site scripting (XSS)opts.sameSite
{Boolean} - [Optional] Cookie which can only be sent in requests originating from the same origin as the target domain. Read more on wikipedia and ietfopts.firstPartyOnly
{Boolean} - [Optional] Deprecated usesameSite
instead
cookies.remove([key], [path], [domain])
[Isomorphic]
remove()
- Remove all cookies on current domainremove(key)
- Remove a cookie on current domainremove(key, path, domain)
:key
{String} - The name of the cookie to create/overwritepath
{String} - [Optional] The path from where the cookie was readable. E.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, read moredomain
{String} - [Optional] The domain from where the cookie was readable. E.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not specified, defaults to the host portion of the current document location (string or null)
cookies.has(key)
[Isomorphic]
Check whether a cookie exists in the current position, returns boolean value
key
{String} - The name of the cookie to check
cookies.keys()
[Isomorphic]
Returns an array of all readable cookies from this location
cookies.send([callback])
[Client]
Send all current cookies to server
Examples:
/* Both Client & Server */
import { Cookies } from 'meteor/ostrio:cookies';
const cookies = new Cookies();
/* Client */
if (Meteor.isClient) {
cookies.set('locale', 'en'); //true
cookies.set('country', 'usa'); //true
cookies.set('gender', 'male'); //true
cookies.get('gender'); //male
cookies.has('locale'); //true
cookies.has('city'); //false
cookies.keys(); //['locale', 'country', 'gender']
cookies.remove('locale'); //true
cookies.get('locale'); //undefined
cookies.keys(); //['country', 'gender']
cookies.remove(); //true
cookies.keys(); //[""]
cookies.remove(); //false
}
/* Server */
if (Meteor.isServer) {
WebApp.connectHandlers.use((req, res, next) => {
cookies = req.Cookies;
cookies.set('locale', 'en'); //true
cookies.set('country', 'usa'); //true
cookies.set('gender', 'male'); //true
cookies.get('gender'); //male
cookies.has('locale'); //true
cookies.has('city'); //false
cookies.keys(); //['locale', 'country', 'gender']
cookies.remove('locale'); //true
cookies.get('locale'); //undefined
cookies.keys(); //['country', 'gender']
cookies.remove(); //true
cookies.keys(); //[""]
cookies.remove(); //false
next(); // Pass request to the next handler
});
}
Alternate Usage
/* Both Client & Server */
import { Cookies } from 'meteor/ostrio:cookies';
/* Client */
if (Meteor.isClient) {
const cookies = new Cookies();
cookies.set('gender', 'male'); //true
cookies.get('gender'); //male
cookies.has('city'); //false
cookies.keys(); //['gender']
}
/* Server */
if (Meteor.isServer) {
const cookie = new Cookies({
auto: false, // Do not bind as a middleware by default
handler(cookies) {
cookies.set('gender', 'male'); //true
cookies.get('gender'); //male
cookies.has('city'); //false
cookies.keys(); //['gender']
}
});
WebApp.connectHandlers.use(cookie.middleware());
}
Running Tests
- Clone this package
- In Terminal (Console) go to directory where package is cloned
- Then run:
Meteor/Tinytest
# Default
meteor test-packages ./
# With custom port
meteor test-packages ./ --port 8888
# With local MongoDB and custom port
MONGO_URL="mongodb://127.0.0.1:27017/cookies-tests" meteor test-packages ./ --port 8888
Support this project:
- Become a patron β support my open source contributions with monthly donation
- Use ostr.io β Monitoring, Analytics, WebSec, Web-CRON and Pre-rendering for a website