Context provided in _app.js can't be consumed in pages in SSR
See original GitHub issueReact v16.3 context provided in pages/_app.js
can be consumed and rendered in pages on the client, but is undefined in SSR. This causes React SSR markup mismatch errors.
Note that context can be universally provided/consumed within pages/_app.js
, the issue is specifically when providing context in pages/_app.js
and consuming it in a page such as pages/index.js
.
- I have searched the issues of this repository and believe that this is not a duplicate.
Expected Behavior
Context provided in pages/_app.js
should be consumable in pages both on the server for SSR and when browser rendering.
Current Behavior
Context provided in pages/_app.js
is undefined when consumed in pages for SSR. It can only be consumed for client rendering.
Steps to Reproduce (for bugs)
In pages/_app.js
:
import App, { Container } from 'next/app'
import React from 'react'
import TestContext from '../context'
export default class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return (
<Container>
<TestContext.Provider value="Test value.">
<Component {...pageProps} />
</TestContext.Provider>
</Container>
)
}
}
In pages/index.js
:
import TestContext from '../context'
export default () => (
<TestContext.Consumer>
{value => value}
</TestContext.Consumer>
)
In context.js
:
import React from 'react'
export default React.createContext()
Will result in:
Context
A large motivation for the pages/_app.js
feature is to be able to provide context persistently available across pages. It’s unfortunate the current implementation does not support this basic use case.
I’m attempting to isomorphically provide the cookie in context so that graphql-react
<Query />
components can get the user’s access token to make GraphQL API requests. This approach used to work with separately decorated pages.
Your Environment
Tech | Version |
---|---|
next | v6.0.0-canary.5 |
node | v9.11.1 |
Issue Analytics
- State:
- Created 5 years ago
- Reactions:53
- Comments:56 (24 by maintainers)
Top GitHub Comments
Basically the issue was exactly what my explanation said here: https://github.com/zeit/next.js/issues/4194#issuecomment-387443497
This solves it: https://github.com/zeit/next.js/pull/4639/commits/00f62f55907d9d3b47104abe4db04d261d5beabe
Unfortunately it doesn’t work as expected with commonschunk on the server. I have some ideas to fix this once and for all, but haven’t had time to implement it yet.