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.
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.
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
}
I hope this solution will solve your problem.
This is an example of the startup function in next JS with not custom server
This repository run startup function without using custom server. Before and after the next JS is loaded, it can be executed respectively.
// before next loading
console.log(process.env.ENV_TEST, '[expected]: undefined') // undefined
// after next loading
const command = process.argv[2]
if (['dev', 'start'].includes(command)) {
require('./node_modules/next/dist/bin/next')
check(init)
}
// function
// function
// function
// next loading check
/** @param {Function} fn */
function check(fn) {
setTimeout(() => {
if (!('LOAD_CHECK' in process.env)) {
setTimeout(check, 0, fn)
return
}
fn()
}, 50)
}
// after init function
function init() {
switch (command) {
case 'dev': {
// here dev script
console.log('run dev')
break
}
case 'start': {
// here start script
console.log('run start')
break
}
}
// commons script
console.log(process.env.ENV_TEST, '[expected]: Hello!!') // 'Hello!!'
}
For more information, see the app.js in this repository