{"id":12007,"library":"server-only-context","title":"Server-Only Context for React Server Components","description":"`server-only-context` is a lightweight utility designed to provide request-scoped context specifically for React Server Components (RSC). It helps mitigate the problem of prop drilling in server-side rendering environments by leveraging React's experimental `cache` function to store and retrieve values associated with the current request. This ensures that context values are isolated between different concurrent server requests, which is crucial for multi-user applications. The current stable version, 0.1.0, indicates it's an early-stage project that is actively developed but may still be subject to changes. Its core differentiator is its exclusive design for the server-side, contrasting with traditional React Context which is primarily client-side or hydrates from server-rendered content. It offers a straightforward API to create getter/setter tuples for managing context values.","status":"active","version":"0.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/manvalls/server-only-context","tags":["javascript","typescript"],"install":[{"cmd":"npm install server-only-context","lang":"bash","label":"npm"},{"cmd":"yarn add server-only-context","lang":"bash","label":"yarn"},{"cmd":"pnpm add server-only-context","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency on 'react: \"next\"' as it relies on experimental React Server Component features.","package":"react","optional":false}],"imports":[{"note":"This library is designed for React Server Components, which primarily use ES Modules. CommonJS require is generally not applicable.","wrong":"const serverContext = require('server-only-context');","symbol":"serverContext","correct":"import serverContext from 'server-only-context';"},{"note":"After defining your context with `export const [getLocale, setLocale] = serverContext('en');`, these functions are imported as named exports from your custom context file.","symbol":"getters/setters","correct":"import { getLocale, setLocale } from '@/context/locale';"}],"quickstart":{"code":"/* src/context/locale.ts */\nimport serverContext from 'server-only-context';\nexport const [getLocale, setLocale] = serverContext<string>('en');\n\n/* src/context/user.ts */\nexport const [getUserId, setUserId] = serverContext<string>('');\n\n/* src/app/layout.tsx */\n// Example of a root layout that might set initial context\n// import { setLocale, setUserId } from '@/context'; // In a real app, combine contexts into one file or use aliases\n// export default function RootLayout({ children }: { children: React.ReactNode }) {\n//   // In a real scenario, you'd extract locale/userId from headers or cookies here\n//   setLocale('en-US'); \n//   setUserId('guest');\n//   return <html><body>{children}</body></html>;\n// }\n\n/* src/app/[locale]/[userId]/page.tsx */\n// This represents a server component page where context is set based on URL params\nimport { setLocale, setUserId } from '@/context/locale'; // Assume these are from a combined context file for brevity\nimport { getLocale, getUserId } from '@/context/user'; // Assume these are from a combined context file for brevity\n\ninterface UserPageProps {\n  params: { \n    locale: string; \n    userId: string; \n  };\n}\n\nasync function MyComponent() {\n  // In a real app, this might be a child component deep in the tree\n  const locale = getLocale();\n  const userId = getUserId();\n\n  return (\n    <div>\n      <p>Hello {userId || 'Guest'}!</p>\n      <p>Current Locale is: {locale || 'Default'}</p>\n      <p>This data was fetched using server-only context.</p>\n    </div>\n  );\n}\n\nexport default async function UserPage({ params: { locale, userId } }: UserPageProps) {\n  setLocale(locale);\n  setUserId(userId);\n\n  // Demonstrate subsequent access within the same request scope\n  const currentLocaleCheck = getLocale();\n  const currentUserIdCheck = getUserId();\n  console.log(`Context set to: locale=${currentLocaleCheck}, userId=${currentUserIdCheck}`);\n\n  return <MyComponent />;\n}","lang":"typescript","description":"This quickstart demonstrates how to define server-only context and then set and retrieve values within a React Server Component structure, mimicking a typical page and its child components."},"warnings":[{"fix":"Ensure `setContextValue(value)` is called in both the relevant layout and page components where context values might change due to navigation.","message":"When navigating on the client side, layouts are not re-rendered by default in React. Therefore, you must explicitly set the context in both the page component and the layout component to ensure consistent values across client-side navigation.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Monitor React's official releases and `server-only-context` updates closely. Be prepared to update dependencies and code if React's experimental APIs change.","message":"This library relies on React's experimental `cache` function and requires `react@next` as a peer dependency. Future updates to React or changes in the `cache` API could introduce breaking changes to `server-only-context`.","severity":"breaking","affected_versions":">=0.1.0"},{"fix":"Ensure that any component calling `get` or `set` functions derived from `serverContext` is a Server Component. Use `\"use client\";` directive to explicitly mark client components where this context should *not* be used.","message":"This library is strictly for server components. Attempting to use `get` or `set` functions within a client component will result in a runtime error, as `cache` is a server-only API.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Exercise caution when using in production. Pin to exact versions and thoroughly test after any updates. Consider contributing to help stabilize the API.","message":"As a version 0.1.0 package, `server-only-context` is in an early development stage. While functional, it may not be fully battle-tested, and its API or internal implementation might evolve rapidly, potentially leading to breaking changes in minor versions.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify that the component where `get*` or `set*` functions are called is a Server Component. Ensure no `\"use client\";` directive is present in the file or any parent component that directly uses this context.","cause":"Attempting to use `server-only-context` functions within a client component or outside of the React Server Component environment.","error":"TypeError: Cannot read properties of undefined (reading 'getCacheForType')"},{"fix":"Ensure you are importing `getLocale` and `setLocale` from the specific file where you defined and exported them (e.g., `import { getLocale } from '@/context/locale';`).","cause":"Incorrectly importing the getter/setter functions. They are named exports from your custom context file, not directly from `server-only-context`.","error":"ReferenceError: getLocale is not defined"},{"fix":"Implement `setContextValue(value)` calls in both your server-rendered layout and server-rendered page components to ensure the context is correctly initialized for all request paths, including those initiated by client navigation.","cause":"The context was not reset or correctly set in both the layout and page components during a client-side navigation, leading to stale or absent values.","error":"MyComponent unexpectedly receives 'undefined' for context values after client navigation."}],"ecosystem":"npm"}