npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

simple-cookie-client

v0.3.1

Published

Simple and isomorphic cookie api, with support for hybrid client-side and server-side rendering applications.

Downloads

182

Readme

simple-cookie-client

ci_on_commit deploy_on_tag

Simple and isomorphic cookie api, with support for hybrid client-side and server-side rendering applications.

usage

install

npm install simple-cookie-client

get a cookie

this library makes it easy to get a cookie in any environment.

by default, this library checks the following cookie storage mechanisms:

  • document.cookie, if the document global is defined (i.e., in a browser)
  • in-memory cache, if the document global was not defined (e.g., if server-side rendering)

for example

import { getCookie, Cookie } from 'simple-cookie-client';

const cookie = getCookie({ name: 'authorization' });
expect(cookie).toBeInstanceOf(Cookie);

you can also specify that you want to only get cookies from a particular storage mechanism

for example

import { getCookie, Cookie, CookieStorageMechanism } from 'simple-cookie-client';

const cookieInBrowser = getCookie({
  name: 'authorization',
  storage: { mechanism: CookieStorageMechanism.BROWSER },
});
expect(cookieInBrowser).toBeInstanceOf(Cookie);

const cookieInMemory = getCookie({
  name: 'authorization',
  storage: { mechanism: CookieStorageMechanism.IN_MEMORY },
});
expect(cookieInMemory).toBeInstanceOf(Cookie);

you can even specify a custom cookie storage mechanism to use

for example

import { createCache } from 'simple-on-disk-cache';

const cookieOnDisk = getCookie({
  name: 'authorization',
  storage: {
    mechanism: CookieStorageMechanism.CUSTOM,
    implementation: createCache({
      directory: {
        s3: {
          bucket: '__your_s3_bucket__',
          prefix: 'path/to/cookies'
        }
      },
    })
  }
})
expect(cookieOnDisk).toBeInstanceOf(Cookie);

set a cookie

setting a cookie operates much like getting a cookie, except you also pass in the value.

import { setCookie } from 'simple-cookie-client';

setCookie({ name: 'authorization', value: '821' }); // note: like with getCookie, you may choose which storage mechanism to use

delete a cookie

same thing with deleting

import { deleteCookie } from 'simple-cookie-client';

deleteCookie({ name: 'authorization' }); // note: like with getCookie, you may choose which storage mechanism to use

parsing out cookies from a header

if you need to manually deal with headers, on the backend for example, this library exposes a simple utility which is able to extract cookies from any header object.

for example, from a set-cookie (case insensitive) header

import { getCookiesFromHeader } from 'simple-cookie-client';

const header = {
  'set-cookie': [
    'NID=511=stuffstuffstuff-SaX-stuffstuffstuff-stuffstuff-stuffstuffstuff; expires=Thu, 06-Apr-2023 14:37:50 GMT; path=/; domain=.coolstuff.com; HttpOnly',
  ],
};
const cookies = getCookiesFromHeader({ header });
expect(cookies.length).toEqual(1);
expect(cookies[0].name).toEqual('NID');
expect(cookies[0].domain).toEqual('.coolstuff.com');

or from a cookie (case insensitive) header

const header = {
  cookie:
    '_ga=123; authorization=opensaysame; __utma=10102256.1994221130.1664978497.1664978497.1664978497.1',
};
const cookies = getCookiesFromHeader({ header });
expect(cookies.length).toEqual(3);
expect(cookies[0].name).toEqual('_ga');
expect(cookies[2].name).toEqual('__utma');

casting cookies into a cookie header string

in case you need to set a cookie header from a list of cookies, this library also exposes a simple way to turn any list of cookies into the header string, compliant with spec.

import { castCookiesToCookieHeaderString } from 'simple-cookie-client';

const string = castCookiesToCookieHeaderString([
  new Cookie({ name: '_ga', value: '123' }),
  new Cookie({ name: 'authorization', value: 'opensaysame' }),
]);
expect(string).toEqual(
  '_ga=123; authorization=opensaysame;',
);

server side rendering support

In serverside rendering, you may need a cookie that is accessible to your clientside application in the document but not in your serverside application context. Typically, the same cookie that is accessible in the browser in the document object - is accessible on the server in the request object sent to your server.

Therefore, this library supports exposing cookies from the request in a way that is isomorphic (i.e., looks the same) to the clientside code you're writing.

For example, in a Next.JS application, you are able to access the req object with getServerSideProps. Here is how you can expose the cookie in that environment:

import { exposeCookieFromReq } from 'simple-cookie-client';

export const getStaticProps = async ({ req }) =>
  exposeCookieFromReq({
    name, // the name of the cookie you want to expose
    req, // the request object next.js was given
  });

And now, any code in your stack can access that cookie without needing to think about whether it gets it from the browser directly or whether it was exposed like above:

const cookie = getCookie({ name }); // this will work both in SSR (if cookie was exposed from req) as well as browser (where cookie is in `document` api)