flâneur — a map of the web's best reading

Refreshing the Next.js App Router When Your Markdown Content Changes - Steve Ruiz

steveruiz.me · 927 words · saved by 1 readers

Are you writing MDX content for a Next.js blog and want to see live reloads when the content changes? Here's how to do it. Install some dependencies: Create a watcher.ts file in the root of your Next.js project. Create a script in your package.json that starts the watcher on dev. Create a component named AutoRefresh. Wrap your root layout.tsx in the AutoRefresh component. Vercel provides excellent documentation of using Markdown / MDX together with Next.js (including with its new App Router). While it's possible to have .mdx files map 1-1 to pages using the file-based routing system, this is impractical for most projects and especially for projects with many dozens or hundreds of content files. For these projects, the answer has been to use remote MDX via the Hashicorp library next-mdx-remote, where content files are created server-side upon first request. This is a great solution, but it has one drawback: the Next.js App Router does not refresh when content in the folder changes. This

Are you writing MDX content for a Next.js blog and want to see live reloads when the content changes? Here's how to do it. The Solution Install some dependencies: npm i -D ws concurrently tsx Create a watcher.ts file in the root of your Next.js project. import fs from "fs" ; import { WebSocketServer } from "ws" ; const CONTENT_FOLDER = "content" ; fs . watch ( CONTENT_FOLDER , { persistent : true , recursive : true } , async ( eventType , fileName ) => { clients . forEach ( ( ws ) => { // do any pre-processing you want to do here... ws . send ( "refresh" ) ; } ) ; } , ) ; const wss = new WebSo

Explore this link on the map →

related reading