I get this error when I run gatsby build. I have not used "document" in my code. Can someone explain what this means?
ERROR
Page data from page-data.json for the failed page "/": {
"componentChunkName": "component---src-pages-index-js", "path": "/", "result": { "pageContext": {} }, "staticQueryHashes": [] }failed Building static HTML for pages - 2.990s
ERROR #95312
"document" is not available during server side rendering.
The reason why this issue appears is because somewhere in your code you are using document
global object and, because gatsby develop
is rendered by the browser, where there are window
and document global objects, it compiles, however, when you run gatsby build
, the code is compiled in the Node server, where there's no window
or document
variables because they are not even defined yet, they are client-side variables parsed in the SSR (Server-Side Rendering).
This is an extreme reduction of what's happening, you can find a more detailed explanation in Debugging HTML Builds docs.
To fix/bypass this issue, you only need to add the following condition where you are using document
object.
if(window !== "undefined"){
// your document or window manipulation
}
You can use both window
or document
in the condition, they are equivalent in terms of bypassing the server-side rendering.
If you are not using document
in your project, the issue may still rise if some of your dependencies (third-party) are using it (i.e: canvas, maps, sliders that uses JavaScript calculations, etc). If that's your scenario, the way to bypass it is to ignore webpacks bundling by adding a null
loader:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html" || stage === "develop-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /bad-module/,
use: loaders.null(),
},
],
},
})
}
}
Where /bad-module/
is a regular expression (test
) (that's why is between slashes, /
). In this case, you need to replace bad-module
for the dependency folder name in node_modules
.