I have a (server-side) function I'd like to run when first starting my next.js server. Ordinarily I'd do something like this in my package.json
script definition: node ./path/to/script.js && next start
. But the script in question imports several resources from "webpacked" code, so that's not so easy. (I know it's possible to turn on es6 support in node.js with --experimental-modules
, but this brings its own problems and I'd rather not go down that rabbit hole)
The best solution I have so far is to create an api endpoint to run these scripts and then either manually hit that endpoint after starting. But it seems like such a hack to do this, and it's possible that this endpoint could be used in some sort of DoS attack if someone found it.
Is there a better solution, something that just allows one to register a function/callback to be run when the app is starting? I figured a likely place would be the next.config.js but I don't see anything likely in the list of possible settings.
I guess you could use the webpack configuration on the next.config file to register a new plugin and run it after the build is done.
module.exports = {
webpack: (config, options) => {
config.plugins.push(
{
apply: (compiler) => {
compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
console.log(".. Run after build")
});
}
}
)
return config
},
}
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