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' });
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.
import { getCookiesFromString } from 'simple-cookie-client';
const cookies = getCookiesFromString('authorization=abc; _ga=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,
req,
});
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 });