Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle server context being refreshed #38580

Merged
merged 2 commits into from Jul 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 22 additions & 6 deletions packages/next/client/components/hooks-server-context.ts
@@ -1,9 +1,25 @@
// @ts-expect-error createServerContext exists on experimental channel
import { createServerContext } from 'react'

export const HeadersContext = createServerContext('HeadersContext', null)
export const PreviewDataContext = createServerContext(
'PreviewDataContext',
null
)
export const CookiesContext = createServerContext('CookiesContext', null)
// Ensure serverContext is not created more than once as React will throw when creating it more than once
// https://github.com/facebook/react/blob/dd2d6522754f52c70d02c51db25eb7cbd5d1c8eb/packages/react/src/ReactServerContext.js#L101
const createContext = (name: string) => {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
if (!global.__NEXT_DEV_SERVER_CONTEXT__) {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
global.__NEXT_DEV_SERVER_CONTEXT__ = {}
}

// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
if (!global.__NEXT_DEV_SERVER_CONTEXT__[name]) {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
global.__NEXT_DEV_SERVER_CONTEXT__[name] = createServerContext(name, null)
}

// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
return global.__NEXT_DEV_SERVER_CONTEXT__[name]
}

export const HeadersContext = createContext('HeadersContext')
export const PreviewDataContext = createContext('PreviewDataContext')
export const CookiesContext = createContext('CookiesContext')