To make Next.js journal page hot reloads while editing the .mdx file
The Problem
If you have a journal created with Next.js and MDX either using mdx-bundler or next-mdx-remote (maybe there's more libs with the same issue), you must've experienced the dreaded manual refresh every time you want to see some changes. The hot reload or fast refresh doesn't work because we are not directly changing a JavaScript or TypeScript files.
With this short article, I'll show you how to enable hot-reload for your journal page by listening to mdx file changes.
Install next-remote-refresh
This library enables hot reload by utilizing websocket by listening to folder changes.
yarn add next-remote-refresh
Update next.config.js
next.config.js
const path = require('path');
const withRemoteRefresh = require('next-remote-refresh')({
// Configure your Next.js project to watch the files you want to refresh
paths: [path.resolve(__dirname, 'src', 'contents')],
});
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// ... your config
};
module.exports = withRemoteRefresh(nextConfig);
Don't forget to restart your server.
I'm listening changes for all files inside src/contents
folder.
Add the hook to _app.tsx
_app.tsx
import { useRemoteRefresh } from 'next-remote-refresh/hook';
function MyApp({ Component, pageProps }: AppProps) {
useRemoteRefresh();
return <Component {...pageProps} />;
}
export default MyApp;
It should work now!