Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlhorky/067049065ffcd84cb207ab513460360b to your computer and use it in GitHub Desktop.
Save karlhorky/067049065ffcd84cb207ab513460360b to your computer and use it in GitHub Desktop.
Express Middleware to Disable Gatsby's window.replaceState()
// Express middleware to disable Gatsby window.replaceState() to
// avoid changing new rewritten URLs back to original URLs
// https://github.com/gatsbyjs/gatsby/blob/c91ed287fd319a345c2f27877e20656826767e92/packages/gatsby/cache-dir/production-app.js#L159-L187
const appJsFilePath = existingGatsbyFiles.find((filePath) =>
/^\/app-[\da-f]+\.js$/.test(filePath),
)!;
const appJsContent = readFileSync(
join(websitePath, 'public', appJsFilePath),
'utf-8',
);
app.use((req, res, next) => {
if (req.url === appJsFilePath) {
res.type('application/javascript');
res.send(
appJsContent.replace(
'const{pagePath:f,location:m}=window;f&&""+f!==m.pathname+(f.includes("?")?m.search:"")&&!(Z.findMatchPath((0,A.Z)(m.pathname,""))||f.match(/^\\/(404|500)(\\/?|.html)$/)||f.match(/^\\/offline-plugin-app-shell-fallback\\/?$/))&&(0,a.navigate)(""+f+(f.includes("?")?"":m.search)+m.hash,{replace:!0});',
// Changed `""+f+` (Gatsby pagePath) to `""+m.pathname+` (window.location.pathname)
'const{pagePath:f,location:m}=window;f&&""+f!==m.pathname+(f.includes("?")?m.search:"")&&!(Z.findMatchPath((0,A.Z)(m.pathname,""))||f.match(/^\\/(404|500)(\\/?|.html)$/)||f.match(/^\\/offline-plugin-app-shell-fallback\\/?$/))&&(0,a.navigate)(""+m.pathname+(f.includes("?")?"":m.search)+m.hash,{replace:!0});',
),
);
return;
}
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment