How do I hook into the startup of a NextJS server so that I can do one-off initialization?
There's a discussion here but so far no solution.
You can use instrumention.ts(or .js) file from nextjs official documentation
This is basically, we export a function named register in a file called instrumention (js/ts) in root directory of your project. In the src/ directory if you use one. Nextjs looks for the file and calls the function whenever server instance is bootstrapped.
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: { instrumentationHook: true },
};
module.exports = nextConfig;
instrumentation.ts
export function register() {
setInterval(() => console.log(new Date()), 2000)
}
Save the file and restart the server. The output only updates on restarting the server. else the previous code will run if you had one in instrumentation.ts file.
now you can see the output below.
Output Output image
Read the full doc here
Just add your code to the next.config.js file.
Something like this should do the trick:
//next.config.js
//imports
module.exports = async (phase, { defaultConfig }) => {
const nextConfig = {...}
console.log("Executes at server startup")
return nextConfig
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With