Skip to content

Commit

Permalink
fix:Put the server phase guard in the right places.
Browse files Browse the repository at this point in the history
  • Loading branch information
greg2012201 committed Oct 31, 2024
1 parent fad83ba commit b860cfd
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ import { stringify, decode, isClientSide, getRenderPhase } from '../common/utils

const ensureClientSide = (options?: OptionsType) => {
if (!isClientSide(options)) {
if (getRenderPhase() === 'server') {
// to prevent crash caused by missing window.document during server rendering phase
return;
}
throw new Error(
'You are trying to access cookies on the server side. Please, use the server-side import with `cookies-next/server` instead.',
);
}
};

const getCookies = (_options?: OptionsType): TmpCookiesObj => {
const getCookies = (_options?: OptionsType): TmpCookiesObj | undefined => {
ensureClientSide(_options);
if (getRenderPhase() === 'server') {
return;
}
const cookies: TmpCookiesObj = {};
const documentCookies = document.cookie ? document.cookie.split('; ') : [];

Expand All @@ -31,15 +30,17 @@ const getCookies = (_options?: OptionsType): TmpCookiesObj => {

const getCookie = (key: string, options?: OptionsType): CookieValueTypes => {
ensureClientSide(options);

const _cookies = getCookies(options);
const value = _cookies[key];
const value = _cookies?.[key];
if (value === undefined) return undefined;
return decode(value);
};

const setCookie = (key: string, data: any, options?: OptionsType): void => {
ensureClientSide(options);
if (getRenderPhase() === 'server') {
return;
}
const _cookieOptions = options || {};
const cookieStr = serialize(key, stringify(data), { path: '/', ..._cookieOptions });
document.cookie = cookieStr;
Expand All @@ -54,6 +55,9 @@ const hasCookie = (key: string, options?: OptionsType): boolean => {
ensureClientSide(options);
if (!key) return false;
const cookies = getCookies(options);
if (!cookies) {
return false;
}
return Object.prototype.hasOwnProperty.call(cookies, key);
};

Expand Down

0 comments on commit b860cfd

Please sign in to comment.