Next.js Cookie Adapter

GitHub Demo 

SSR-compatible state persistence using cookies. Unlike localStorage, cookies are available on both server and client, enabling true server-side rendering with pre-populated state.

Why Use This 

  • SSR support - State available during server render, no hydration mismatch
  • Automatic hydration - Client automatically picks up server state
  • Cookie options - Full control over expiry, security, and scope
  • Validation - Validate cookie data before restoring

Installation 

npm
pnpm
yarn
npm install contection-next-cookie-adapter
pnpm add contection-next-cookie-adapter
yarn add contection-next-cookie-adapter

Usage 

import { createNextCookieAdapter } from "contection-next-cookie-adapter";

const cookieAdapter = createNextCookieAdapter({
keys: ["theme", "user"],
cookieOptions: {
httpOnly: false,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 7, // 7 days
},
});

cookieAdapter.attach(AppStore);

Options 

OptionTypeDescription
keysstring[]Store keys to persist
cookieOptions.httpOnlybooleanfalse for client access
cookieOptions.securebooleantrue for HTTPS only
cookieOptions.sameSitestring"lax", "strict", or "none"
cookieOptions.maxAgenumberExpiry in seconds
validate(data) => booleanValidate before restoring

With Validation 

const cookieAdapter = createNextCookieAdapter({
keys: ["theme", "preferences"],
cookieOptions: {
httpOnly: false,
secure: true,
sameSite: "lax",
maxAge: 60 * 60 * 24 * 30, // 30 days
},
validate: (data) => {
if (data.theme && !["light", "dark", "system"].includes(data.theme)) {
return false;
}
return true;
},
});

Server Component Access 

// app/layout.tsx
import { cookies } from "next/headers";

export default function RootLayout({ children }) {
const theme = cookies().get("theme")?.value || "light";

return (
<html data-theme={theme}>
<body>
<AppStore value={{ theme }}>
{children}
</AppStore>
</body>
</html>
);
}

Comparison with Storage Adapter 

FeatureStorage AdapterCookie Adapter
SSR supportNoYes
Server accessNoYes
Size limit~5MB~4KB
Sent with requestsNoYes
Return to navigation