README
simple-cookie-client
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
import { getCookie } from 'simple-cookie-client';
const cookie = getCookie({ name: 'authorization' }); // returns `null` or `Cookie`
Supports both browser and server side env.
set a cookie
import { setCookie } from 'simple-cookie-client';
setCookie({ name: 'authorization', '821' });
Supports both browser and server side env.
delete a cookie
import { deleteCookie } from 'simple-cookie-client';
deleteCookie({ name: 'authorization' });
Supports both browser and server side env.
parsing out cookies from a cookie header string
import { getCookiesFromString } from 'simple-cookie-client';
const cookies = getCookiesFromString('authorization=abc; _ga=123') // => [Cookie({ name: 'authorization', value: 'abc'}), Cookie({ name: '_ga', value: '123' })]
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)