next.js: Context provided in _app.js can't be consumed in pages in SSR
React 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 |
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 51
- Comments: 56 (26 by maintainers)
Commits related to this issue
- Upgrade next to 6.1.1-canary.4 Fixes issue with `React.createContext()` per https://github.com/zeit/next.js/issues/4194 — committed to zarathustra323/fortnight-web by zarathustra323 8 years ago
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.
We’ll be tackling this after webpack 4 lands, as it’ll make it easier to implement a fix for this issue.
Progress on the webpack 4 branch can be followed here: #4639, there’s no way to give a timeline for this specific issue as this is a bug that has to be investigated to come up with a fix. It has my priority after #4639 lands.
It’s still happening in Next.js 11…
I wanted to mention this will become more important as heavily used libraries will soon start publishing versions that use the new context API instead.
If you render that custom app component as the root in each of your
pages/then it’ll remount when navigating to another page on the client. This makes it difficult to add things like page transitions or global react state across different pages.Hi, any updates on this issue?
No update. I’ve been working on upgrading to webpack 4.
For now i’ve worked around this issue by avoiding _app.js and wrapping every single page like so:
I can also confirm i am having problems with context api in SSR on 8.1.0 and i had to downgrade again.
Yeah this is the root problem here. For the server compilation only, both
index.jsand_app.jsare separately bundled into two commonjs modules that are run in node. This server compilation also uses a special webpack “externals” condition so that all non-source modules (basically anything fromnode_modulesthat isn’t nextjs) are resolved through regular noderequirecalls. This prevents webpack from bundling modules intoindex.jsand_app.jsthat already work in a nodejs env. However, your'components/context'file does not match that “externals” condition (and shouldn’t since it must be transpiled). This causes the module to be included in both of the commonjs modules produced forindex.jsand_app.js.Unfortunately I don’t think there’s any way to create a commons chunk and have it load properly when targeting node. Maybe another solution could involve bundling
_app.jsand_document.jswith each page module. I think that would also require some changes to how we import the app, document, and requested page.Edit to show how that might look:
Instead of importing app, document, and page as separate modules, we could destructure all three from a single page bundle:
@timneutkens With this fix, is
Context.Provideronly permitted to be used from _app.js? For me, it works when I set the provider in _app.js, butContext.Consumerdoes not get the values whenContext.Provideris defined in a file in pages. Is this by design? Ideally, I’d like to setContext.Providerat the page, not app, level, then useContext.Consumerin child components.Next version: 7.0.0
@joeporpeglia @timneutkens I ran into this last night and spent a couple hours banging my head on the wall. @mtford90 thanks for suggesting the workaround.
Is there any proposal that could resolve this issue?
@brad-decker I don’t believe there’s any way to make commons chunks work when targeting node 😞. I also don’t think the dynamic imports you provided in that example would work as long as the server renderer
require’s_app.jsand the currently requested page separately. https://github.com/zeit/next.js/blob/aec4c00214a82097d07295b00f0af5f4eb24167b/server/render.js#L59-L66Is it possible to create a similar “main” commons chunk for the server bundles? This issue doesn’t seem like a problem for the client bundles (
.next/bundles/pages/*.jsand.next/static/commons/main-*.js) since thecreateContext()call only exists in the main chunk. I haven’t been able to get a working example, but I’ll keep messing around with the idea.Will this be fixed? This problem break lots of behavior from module’s local variable, and I think it’s a important issue. ex: react-act https://github.com/pauldijou/redux-act#types
So, since Next 5 we run webpack 2 times, once for the server, once for the client. Both have different configurations.
On the server webpack will pack every page into it’s own bundle (
entrypoint), which ends up in.next/dist. This bundle holds everything, including all imported components etc.Say you have 2 pages that both import
Headerit will end up in both page 1 and page 2’s bundle.Because of this module state / singletons don’t work, since if you server render page 1, and it holds a module state inside the component, for example:
It won’t shared between server rendering of 2 pages.
From what I’ve understood looking at the new context API, this is exactly what the context API depends on (local module state). So if you have
_app.jsand you initialize it there, and then try to access the context frompages/index.js, they’ll have 2 different context module states.I hope this explains the issue.
I’m not entirely sure how we can fix this issue. In Next 4 and below we emitted every possible file into
.next/dist, and then, because we only applied Babel, the paths whenimporting were still correct, but with webpack this works a little different, since it parses import/export and turns it into a dependency tree, and also bundles to a file, not 1-1 into the specified directory.