Skip to content

Commit

Permalink
Format all files with Prettier.
Browse files Browse the repository at this point in the history
  • Loading branch information
greg2012201 committed Aug 23, 2023
1 parent 72026f3 commit d5c32e8
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 102 deletions.
28 changes: 14 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

Getting, setting and removing cookies with NEXT.JS

- can be used on the client side, anywhere
- can be used for server side rendering in getServerSideProps
- can be used in API handlers
- can be used on the client side, anywhere
- can be used for server side rendering in getServerSideProps
- can be used in API handlers

## Installation

Expand Down Expand Up @@ -104,16 +104,16 @@ import React from 'react';
import { getCookies, getCookie, setCookie, deleteCookie } from 'cookies-next';

const Home = () => {
return <div>page content</div>;
return <div>page content</div>;
};

export const getServerSideProps = ({ req, res }) => {
setCookie('test', 'value', { req, res, maxAge: 60 * 6 * 24 });
getCookie('test', { req, res });
getCookies({ req, res });
deleteCookie('test', { req, res });
setCookie('test', 'value', { req, res, maxAge: 60 * 6 * 24 });
getCookie('test', { req, res });
getCookies({ req, res });
deleteCookie('test', { req, res });

return { props: {} };
return { props: {} };
};

export default Home;
Expand Down Expand Up @@ -253,11 +253,11 @@ is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5

Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7).

- `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
- `false` will not set the `SameSite` attribute.
- `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
- `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
- `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
- `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
- `false` will not set the `SameSite` attribute.
- `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
- `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
- `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.

More information about the different enforcement levels can be found in
[the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7).
Expand Down
146 changes: 73 additions & 73 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,101 +5,101 @@ export { CookieValueTypes } from './types';
const isClientSide = (): boolean => typeof window !== 'undefined';

const stringify = (value: string = '') => {
try {
const result = JSON.stringify(value);
return (/^[\{\[]/.test(result)) ? result : value;
} catch (e) {
return value;
}
try {
const result = JSON.stringify(value);
return /^[\{\[]/.test(result) ? result : value;
} catch (e) {
return value;
}
};

const decode = (str: string): string => {
if (!str) return str;
if (!str) return str;

return str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
return str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
};

export const getCookies = (options?: OptionsType): TmpCookiesObj => {
let req;
if (options) req = options.req;
if (!isClientSide()) {
// if cookie-parser is used in project get cookies from ctx.req.cookies
// if cookie-parser isn't used in project get cookies from ctx.req.headers.cookie
if (req && req.cookies) return req.cookies;
if (req && req.headers && req.headers.cookie) return parse(req.headers.cookie);
return {};
}
let req;
if (options) req = options.req;
if (!isClientSide()) {
// if cookie-parser is used in project get cookies from ctx.req.cookies
// if cookie-parser isn't used in project get cookies from ctx.req.headers.cookie
if (req && req.cookies) return req.cookies;
if (req && req.headers && req.headers.cookie) return parse(req.headers.cookie);
return {};
}

const _cookies: TmpCookiesObj = {};
const documentCookies = document.cookie ? document.cookie.split('; ') : [];
const _cookies: TmpCookiesObj = {};
const documentCookies = document.cookie ? document.cookie.split('; ') : [];

for (let i = 0, len = documentCookies.length; i < len; i++) {
const cookieParts = documentCookies[i].split('=');
for (let i = 0, len = documentCookies.length; i < len; i++) {
const cookieParts = documentCookies[i].split('=');

const _cookie = cookieParts.slice(1).join('=');
const name = cookieParts[0];
const _cookie = cookieParts.slice(1).join('=');
const name = cookieParts[0];

_cookies[name] = _cookie;
}
_cookies[name] = _cookie;
}

return _cookies;
return _cookies;
};

export const getCookie = (key: string, options?: OptionsType): CookieValueTypes => {
const _cookies = getCookies(options);
const value = _cookies[key];
if (value === undefined) return undefined;
return decode(value);
const _cookies = getCookies(options);
const value = _cookies[key];
if (value === undefined) return undefined;
return decode(value);
};

export const setCookie = (key: string, data: any, options?: OptionsType): void => {
let _cookieOptions: any;
let _req;
let _res;
if (options) {
const { req, res, ..._options } = options;
_req = req;
_res = res;
_cookieOptions = _options;
}

const cookieStr = serialize(key, stringify(data), { path: '/', ..._cookieOptions });
if (!isClientSide()) {
if (_res && _req) {
let currentCookies = _res.getHeader('Set-Cookie');

if(!Array.isArray(currentCookies)){
currentCookies = !currentCookies ? [] : [String(currentCookies)];
}
_res.setHeader('Set-Cookie', currentCookies.concat(cookieStr));

if (_req && _req.cookies) {
const _cookies = _req.cookies;
data === '' ? delete _cookies[key] : _cookies[key] = stringify(data);
}

if (_req && _req.headers &&_req.headers.cookie) {
const _cookies = parse(_req.headers.cookie);

data === '' ? delete _cookies[key] : _cookies[key] = stringify(data);

_req.headers.cookie = Object.entries(_cookies).reduce((accum, item) => {
return accum.concat(`${item[0]}=${item[1]};`);
}, '');
}
}
} else {
document.cookie = cookieStr;
}
let _cookieOptions: any;
let _req;
let _res;
if (options) {
const { req, res, ..._options } = options;
_req = req;
_res = res;
_cookieOptions = _options;
}

const cookieStr = serialize(key, stringify(data), { path: '/', ..._cookieOptions });
if (!isClientSide()) {
if (_res && _req) {
let currentCookies = _res.getHeader('Set-Cookie');

if (!Array.isArray(currentCookies)) {
currentCookies = !currentCookies ? [] : [String(currentCookies)];
}
_res.setHeader('Set-Cookie', currentCookies.concat(cookieStr));

if (_req && _req.cookies) {
const _cookies = _req.cookies;
data === '' ? delete _cookies[key] : (_cookies[key] = stringify(data));
}

if (_req && _req.headers && _req.headers.cookie) {
const _cookies = parse(_req.headers.cookie);

data === '' ? delete _cookies[key] : (_cookies[key] = stringify(data));

_req.headers.cookie = Object.entries(_cookies).reduce((accum, item) => {
return accum.concat(`${item[0]}=${item[1]};`);
}, '');
}
}
} else {
document.cookie = cookieStr;
}
};

export const deleteCookie = (key: string, options?: OptionsType): void => {
return setCookie(key, '', { ...options, maxAge: -1 });
return setCookie(key, '', { ...options, maxAge: -1 });
};

export const hasCookie = (key: string, options?: OptionsType): boolean => {
if (!key) return false;
export const hasCookie = (key: string, options?: OptionsType): boolean => {
if (!key) return false;

const cookie = getCookies(options);
return cookie.hasOwnProperty(key);
const cookie = getCookies(options);
return cookie.hasOwnProperty(key);
};
10 changes: 5 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { CookieSerializeOptions } from 'cookie';
import { IncomingMessage, ServerResponse } from "http";
import { IncomingMessage, ServerResponse } from 'http';

export interface OptionsType extends CookieSerializeOptions {
res?: ServerResponse;
req?: IncomingMessage & {
cookies?:{ [key: string]: string; } | Partial<{ [key: string]: string}>
}
cookies?: { [key: string]: string } | Partial<{ [key: string]: string }>;
};
}

export type TmpCookiesObj = { [key: string]: string } | Partial<{ [key: string]: string}>;
export type CookieValueTypes = string | undefined;
export type TmpCookiesObj = { [key: string]: string } | Partial<{ [key: string]: string }>;
export type CookieValueTypes = string | undefined;
20 changes: 10 additions & 10 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./lib",
"strict": true
},
"include": ["src"],
"exclude": ["node_modules", "tib", "**/__tests__/*"]
}
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./lib",
"strict": true
},
"include": ["src"],
"exclude": ["node_modules", "tib", "**/__tests__/*"]
}

0 comments on commit d5c32e8

Please sign in to comment.