If you set up an MDX
environment in your Next.js
project with next-mdx-remote
(related post), unfortunately you will immediately notice your browser doesn't refresh when you save your MDX file.
This is because when you use next-mdx-remote
to load up your MDX files, you don't explicitly import the MDXs anywhere in your project so Next.js
doesn't know something has been updated. (see here for more info)
Lucky for us, the same author who created next-mdx-remote
also made a library called next-remote-watch
that helps us achieve the live-reload as we change our MDX files.
Installation and setup is actually pretty easy:
npm i -D next-remote-watch
This installs the cli, next-remote-watch
and per documentation, it's a drop-in replacement for your next dev
command.
The cli takes file paths as its positional arguments so if your MDX files are located in, say ./mdx
, you can run the cli like below:
npx next-remote-watch ./mdx
Or you can add an npm script:
{
"scripts": {
"dev": "next dev",
"dev:watch": "next-remote-watch ./mdx"
}
}
One important caveat is that next-remote-watch
is said to rely on some undocumented APIs of Next.js
(see here), it might break if you update your Next.js
version in the future—I've confirmed it works with next@12.3.1
which is the current latest as of 10/20/2022.
So It'd be safer not to overwrite your existing npm dev script
and just create another script like dev:watch
above. (this is also suggested here: MDX Remote Example).
Now, if you run npm run dev:watch
instead of npm run dev
—assuming your script is configured like above—and save one of your MDX files after editing, you'll see your browser will refresh automatically.
And that's how you get auto-refresh feature when you're using next-mdx-remote
!
If you're still here and want to have something even faster and pleasant than a full browser refresh, there's actually a way to do a fast refresh per Dan Abramov's comment.
I use his suggested workaround for this website as well, and it's been working quite well so far without any major issue.
One hurdle to use this solution is that it requires you to modify next-remote-watch
source code, so you have to find a way to use this modified version in your project, not through the officially released package in npm
.
I personally solved this by forking the next-remote-watch
repo, and including this fork as a git submodule
of my website repo. And then I use npm workspace
feature to use this modified next-remote-watch
in my website project's npm script.
This way I could pull the updates from the upstream repo (the original) if necessary while enjoying the modification I made to the fork.
Feel free to check out my repo if you're interested in setting this up: sookmax/website.
Useful links: