nextjs-server-context
v1.0.7
Published
[](https://www.npmjs.com/package/nextjs-server-context) [](LICENSE) [and.getOrThrow() - 📦 ESM-ready with proper
exportsmapping
📦 Installation
yarn add nextjs-server-context
# or
npm install nextjs-server-context🧠 Usage with Zod
// lib/server-context.ts
import { createServerContextWithZod } from "nextjs-server-context/zod";
import { z } from "zod";
export const serverContext = createServerContextWithZod(
{
params: {
id: z.string()
},
searchParamsShape: {
tab: z.string().optional()
}
},
"sidebar" // Optional layout slots; 'children' is added automatically
);⚛️ In layout.tsx
import { serverContext } from "@/lib/server-context";
const Layout = serverContext.layout.Wrapper(({ children, sidebar }) => {
return (
<div className="layout">
<aside>{sidebar}</aside>
<main>{children}</main>
</div>
);
});
export default Layout;⚛️ In page.tsx
import { serverContext } from "@/lib/server-context";
const Page = serverContext.page.Wrapper(({ params, searchParams }) => {
return (
<div>
<h1>User ID: {params.id}</h1>
<p>Tab: {searchParams?.tab ?? "none"}</p>
</div>
);
});
export default Page;🧩 API
createServerContext()
Create a raw context without validation.
import { createServerContext } from "nextjs-server-context";
const ctx = createServerContext();
ctx.set("params", { id: "abc" });
ctx.getOrThrow(); // safe accesscreateServerContextWithZod(options, ...slots)
import { createServerContextWithZod } from "nextjs-server-context/zod";params: Zod schema for dynamic route paramssearchParamsShape: Optional Zod schema for query params...slots: Optional layout slot names (e.g.'sidebar','header')'children'is always auto-included for layouts
Returns:
page.Wrapper(Component)layout.Wrapper(Component)get(),getOrThrow(),set(...)
🛠️ Scripts
| Script | Description |
| --------------------- | ----------------------------- |
| yarn build | Builds the library using Vite |
| yarn prepublishOnly | Ensures build before publish |
🧪 Tech Stack
📄 License
Apache License 2.0 – see LICENSE
👤 Author
Maintained by MDReal Aliyev
