The missing server context for Next.js App Directory.
npm install @sodefa/next-server-contextThe missing server context for Next.js App Directory.
``bash`
pnpm add @sodefa/next-server-context
/app/[myParam]/page.tsx
`tsx
import { pageContext } from '@sodefa/next-server-context'
import { NestedServerComponent } from './NestedServerComponent'
export default pageContext.Wrapper(({ params, searchParams }) => {
return (
<>
/app/[myParam]/NestedServerComponent.tsx
`tsx
import { pageContext } from '@sodefa/next-server-context'export const NestedServerComponent = () => {
const { params, searchParams } = pageContext.getOrThrow()
return
NestedServerComponent: {params.myParam}
}
`Custom Context
/myContext.ts
`ts
import { createServerContext } from '@sodefa/next-server-context'const myContext = createServerContext<{
myValue: string
}>()
`/ParentComp.tsx
`tsx
import { myContext } from './myContext'export const ParentComp = () => {
myContext.set({ myValue: 'hi there' })
return
}
`/ChildComp.tsx
`tsx
import { myContext } from './myContext'export const ChildComp = () => {
const { myValue } = myContext.getOrThrow()
return
ChildComp: {myValue}
}
`Zod Context
/app/zod/[singleParam]/[...deepParams]/myContext.ts
`ts
import { createServerContextWithZod } from '@sodefa/next-server-context'
import { z } from 'zod'export const myContext = createServerContextWithZod(
z.object({
params: z.object({
singleParam: z.string(),
deepParams: z.array(z.string()),
}),
searchParams: z
.object({
p1: z.string().optional(),
p2: z.array(z.string()).optional(),
})
.catchall(z.union([z.string(), z.array(z.string())])), // Allow additional search params (optional)
})
)
`/app/zod/[singleParam]/[...deepParams]/page.tsx
`tsx
import { NestedServerComponent } from './NestedServerComponent'
import { myContext } from './myContext'export default myContext.Wrapper(() => {
return (
<>
Page with a lot of Params
>
)
})
`/app/zod/[singleParam]/[...deepParams]/NestedServerComponent.tsx
`tsx
import { myContext } from './myContext'export const NestedServerComponent = () => {
const { params, searchParams } = myContext.getOrThrow()
return (
{JSON.stringify({ params, searchParams }, null, 2)}
)
}
``