Skip to content

Commit

Permalink
Handle server context being refreshed (#38580)
Browse files Browse the repository at this point in the history
Temporary fix for refreshing of serverContext. We'll want to make a change for development with `createServerContext` to React itself in the future.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
  • Loading branch information
timneutkens committed Jul 13, 2022
1 parent 8425412 commit 13557ea
Showing 1 changed file with 22 additions and 6 deletions.
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')

0 comments on commit 13557ea

Please sign in to comment.