Next.js run function/script when starting app

Viewed 5902

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.

2 Answers

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
    },
}

Could it be possible to run the api after entering the code?

_app.js

const MyApp({pageProps}) {
   useEffect(() => {
   /* call to run API on app mount */
      return ( /* Call to clean up after app unmounted*/);
   },[])

   return (
      <Component {...pageProps} />
   );
}
export default MyApp;

Another solution could be using a Next's getServerSideProps or getStaticProps on the index/entry point for the app

index.js

export default function foo({props}) {
   /* Do something */
   return( /* return something to renderer */);
}

export function getServerSideProps() {
   const caller = fetch(/* Return from running API endpoint*/)
   return (
      props: caller;
   )
}

both of the get* functions from Next.js will run before the component renders to ensure that the data has been fetched. They are used for data fetching, but I don't see why they couldn't be used as a hack to force the API to run near launch.

Related