next-client-cookies
Version:
SSR and client support for Next.js v13 cookies (app directory)
84 lines • 2.96 kB
JavaScript
"use client";
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
import React, { useContext, useEffect, useMemo } from "react";
import jsCookies from "js-cookie";
import { ServerInsertedHTMLContext } from "next/navigation";
import { Ctx } from "./context";
import { useSecureCookies } from "./secure";
const windowVarName = "__cookies_commands";
const CookiesProvider = /* @__PURE__ */ __name(({ value, children }) => {
const cookies = useCookieRecords(value);
return /* @__PURE__ */ React.createElement(Ctx.Provider, {
value: cookies
}, children);
}, "CookiesProvider");
const SecureCookiesProvider = /* @__PURE__ */ __name(({ value, children }) => {
const secureValue = useSecureCookies(value);
const cookies = secureValue ? useCookieRecords(secureValue) : null;
return /* @__PURE__ */ React.createElement(Ctx.Provider, {
value: cookies
}, children);
}, "SecureCookiesProvider");
const useCookieRecords = /* @__PURE__ */ __name((value) => {
const insertedHTML = useContext(ServerInsertedHTMLContext);
const cookies = useMemo(() => {
const map = Object.fromEntries(value.map((c) => [
c.name,
c.value
]));
return {
get: (name) => name == null ? {
...map
} : map[name],
set: (...args) => {
insertedHTML?.(() => getCookieCommandHtml("set", ...args));
map[args[0]] = args[1];
},
remove: (...args) => {
insertedHTML?.(() => getCookieCommandHtml("remove", ...args));
delete map[args[0]];
}
};
}, [
value,
insertedHTML
]);
useEffect(() => {
const commands = window[windowVarName] || [];
if (!commands.length)
return;
for (const command of commands) {
runCookieCommand(command);
}
}, []);
return cookies;
}, "useCookieRecords");
const getCookieCommandHtml = /* @__PURE__ */ __name((...command) => /* @__PURE__ */ React.createElement("script", {
dangerouslySetInnerHTML: {
__html: `window.${windowVarName} = window.${windowVarName} || [];window.${windowVarName}.push(${JSON.stringify(command).replaceAll("</", "<\\/")});`
}
}), "getCookieCommandHtml");
const runCookieCommand = /* @__PURE__ */ __name((command) => {
if (typeof window === "undefined")
return;
switch (command[0]) {
case "set": {
jsCookies.set(command[1], command[2], command[3] && deserializeCookieAttributes(command[3]));
break;
}
case "remove": {
jsCookies.remove(command[1], command[2] && deserializeCookieAttributes(command[2]));
break;
}
}
}, "runCookieCommand");
const deserializeCookieAttributes = /* @__PURE__ */ __name((attributes) => ({
...attributes,
expires: typeof attributes.expires === "string" ? new Date(attributes.expires) : attributes.expires
}), "deserializeCookieAttributes");
export {
CookiesProvider,
SecureCookiesProvider
};
//# sourceMappingURL=provider.mjs.map