Created
April 16, 2024 16:32
-
-
Save karlhorky/067049065ffcd84cb207ab513460360b to your computer and use it in GitHub Desktop.
Express Middleware to Disable Gatsby's window.replaceState()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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