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:

screen shot 2018-04-23 at 2 29 29 pm

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

Most upvoted comments

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…

Does this mean projects following the examples for react-redux, etc will have broken SSR? I am having SSR problems after migrating to wrapping my _app.js in a hoc rather than all my individual pages. @ckeeney nope, since they still use the old React context.

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:

// lib/page.js
import * as React from "react";
import urlContext from "./urlContext";

export default (PageComponent) => {
  return class Page extends React.Component {
    public static async getInitialProps(initialProps) {
      const { req } = initialProps
      const url = req && req.url;
      let props = { url };

      const getInitialProps = PageComponent.getInitialProps;

      if (getInitialProps) {
        props = {
          ...props,
          ...getInitialProps(initialProps)
        }
      }

      return props;
    }

    public render() {
      const url = this.props.url;

      return (
        <urlContext.Provider value={url}>
          <PageComponent/>
        </urlContext.Provider>
      );
    }
  }
}

// pages/index.js
import page from 'lib/page.js'

export default page(() => {
    return (
        <div>A page</div>
    )
})

I can also confirm i am having problems with context api in SSR on 8.1.0 and i had to downgrade again.

Or is it the case that both times it is imported from the various entry points that the module state is essentially initialized again so that even though the code is split out each entry point is creating its own in-memory allocation for the code contained in the common chunk?

Yeah this is the root problem here. For the server compilation only, both index.js and _app.js are 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 from node_modules that isn’t nextjs) are resolved through regular node require calls. This prevents webpack from bundling modules into index.js and _app.js that 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 for index.js and _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.js and _document.js with 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:

let { Page, Document, App } = await requirePage(page, {dir, dist});

@timneutkens With this fix, is Context.Provider only permitted to be used from _app.js? For me, it works when I set the provider in _app.js, but Context.Consumer does not get the values when Context.Provider is defined in a file in pages. Is this by design? Ideally, I’d like to set Context.Provider at the page, not app, level, then use Context.Consumer in 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.js and the currently requested page separately. https://github.com/zeit/next.js/blob/aec4c00214a82097d07295b00f0af5f4eb24167b/server/render.js#L59-L66

Is 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/*.js and .next/static/commons/main-*.js) since the createContext() 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 Header it 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:

let timesRendered = 0

export default () => {
  timesRendered++
  return <div>test</div>
}

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.js and you initialize it there, and then try to access the context from pages/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 when importing 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.