Found a change in next.config.js. Restart the server to see the changes in effect
Deepankar Bhade /
event - compiled successfully in 9.2s (227 modules) wait - compiling /... event - compiled successfully in 782 ms (307 modules)> Found a change in next.config.js. Restart the server to see the changes in effect.
Looks Familiar? If you're next.js developer there's a good chance that you have encountered this message in the terminal on changing the next.config.js
.
So what is this blogpost even around?
I was curious to know how does next.js knows that I have modified the file, to start my expedition I just dived into the Next.js source code and saw the implementation.
The implementation is pretty simple, let's try to build something similar to it. So let's begin by creating a next.config.js
and watch.js
inside a directory.
Next.js uses watchFile
to listen for file changes, the interface of fs.watchFile
is as follows:
ABOUT THE FUNCTIONfs.watchFile(filename[, options], listener)Watches for changes on
filename
. The callbacklistener
will be called each time the file is accessed. The listener gets two arguments the current stat object and the previous stat, these are of the typeStats
fs.Stats
object provides information about a file. You can refer to the entire interface here . We will be using thesize
property which returns the size of the file in bytes helping us to identify if the file was modified or not.
Let's create a dummy config file.
const config = { name: 'Deepankar', age: 20, };
And then the watcher implementation, which would call the listener function based on the size stats. The greater than 0 check makes sure that the file isn't deleted.
const { watchFile } = require('fs'); const configFile = `next.config.js`; watchFile(`${process.cwd()}/${configFile}`, (cur, prev) => { if (cur.size > 0 || prev.size > 0) { console.log( `\n> Found a change in ${configFile}. Restart the server to see the changes in effect.` ); } });
Now run node watch.js
and modify the file and voila!
Here's a Demo
So yeah it was pretty simple but I love to understand how things work behind the scenes. here's that part from next.js source code .
if (command === 'dev') { const { CONFIG_FILES } = require('../shared/lib/constants') const { watchFile } = require('fs') for (const CONFIG_FILE of CONFIG_FILES) { watchFile(`${process.cwd()}/${CONFIG_FILE}`, (cur: any, prev: any) => { if (cur.size > 0 || prev.size > 0) { console.log( `\n> Found a change in ${CONFIG_FILE}. Restart the server to see the changes in effect.` ) } }) } }
Next.js loops over the CONFIG_FILES
which are basically ['next.config.js', 'next.config.mjs']
depending on if you're using the ES6/CJS flavour. The rest of the code is exactly how we did it.
That's it! As much as I loved writing this blog, I hope you folks found this interesting too. There are gonna more such "Next.js deep dive" blogs coming up soon so stay tuned and follow me on Twitter for updates.