Last active
June 23, 2023 18:47
-
-
Save ariefurtado/e2649317d5e770e9e882de040dc769d9 to your computer and use it in GitHub Desktop.
This snippet is useful to force nextjs to do a full page reload.
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
/** | |
* Whenever you're working with web-components and nextjs in development mode, it is possible that the "Fast Refresh" feature | |
* of nextjs don't re-render your web-component. It's a little bit stressful that you have to reload the page manually every time | |
* you update something. (thats why we have HMR and nextsjs Fast Refresh) | |
* | |
* For anyone in need of a way to force the full page reload whenever the "Fast Refresh" occurs, I've made a simple snippet that | |
* uses nextjs internal websocket to listen for that. | |
* | |
* One potential downside to this approach is that it relies on internal functionality of Next.js, | |
* which could potentially change in future versions and break your code. However, as long as you're | |
* aware of this potential issue and you're prepared to update your code if necessary, I think this is a great solution. | |
* | |
* OK, but where do I call this function ?! | |
* The best place I find out to put this, is within the "_app.tsx". | |
* ex: | |
* | |
* import { forceFullPageReloadOnFastRefresh } from './force-full-page-reload.ts'; | |
* | |
* useEffect(() => { | |
* forceFullPageReloadOnFastRefresh(); | |
* }, []); | |
**/ | |
let isReloading = false; // This flag is used in the function to carefully trigger a reload only once per build. | |
export const forceFullPageReloadOnFastRefresh = async () => { | |
const webs = await import('next/dist/client/dev/error-overlay/websocket'); | |
webs.addMessageListener((evt) => { | |
try { | |
const data = JSON.parse(evt.data); | |
if (!isReloading && data.event !== 'pong' && data.action === 'built') { | |
isReloading = true; | |
location.reload(); | |
} | |
} catch { | |
// Silent... | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment