next-compute-js icon indicating copy to clipboard operation
next-compute-js copied to clipboard

DocumentContext not available inside _document when served by Fastly

Open jonasthiesen opened this issue 2 years ago • 2 comments

The DocumentContext that is usually available is undefined when your page has getServerSideProps and is served by Fastly.

I have made a reproduction so you can see the behavior:
https://github.com/jonasthiesen/fastly-document-context-bug

jonasthiesen avatar Feb 16 '23 09:02 jonasthiesen

I have investigated this a bit and have figured out what’s going on.

It looks like Next.js is coded not to let Document be dynamic when it’s being run with NEXT_RUNTIME = 'edge'.

Something like this is hardcoded in the Next.js source code (next/packages/next/server/render.tsx):

      const documentElement = (htmlProps: any) => {
        if (process.env.NEXT_RUNTIME === 'edge') {
          return (Document as any)()
        } else {
          return <Document {...htmlProps} {...docProps} />
        }
      }

You can see see here that those htmlProps values are being thrown away.

The reason that in the repro the context appears to work when getServerSideProps() is removed is when that function is missing, then Next.js has all the information to render the page at build time, so it is no longer dynamic, and is instead rendered using SSG (server side generation). The output of the page is statically rendered into an html file, and in fact you’ll see the full output (including the rendered JSON of the context object) showing up in the /.next/server/pages/index.html file generated by next build.

Since this version of the next runtime emulates NextServer in the context of Compute@Edge JavaScript, an argument can be made that NEXT_RUNTIME = 'edge' is a bug. However this setting avoids the loading of a bunch of other modules that cause problems in Compute@Edge. This is something that may be possible to fix in the future but it will take some work.

harmony7 avatar Mar 08 '23 09:03 harmony7

Thanks for looking into this!

jonasthiesen avatar Mar 09 '23 09:03 jonasthiesen