Adding Scripts to Next.js

I needed to add a queue processing script to my Next.js app, and really wanted to use the Next.js compilation chain to build it so that I wouldn’t have to set up an additional build chain for just one script. It turns out that it’s pretty easy to do.

Adding an extra entry to the webpack configuration will cause an extra script to be output during the build process. My script’s name was src/queue.js. I added it to my entries by modifying next.config.js.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
module.exports = webpack(config, {isServer}) {
  if (isServer) {
    return {
      ...config,
      entry() {
        return config.entry().then(entry => {
          return Object.assign({}, entry, {
            queue: "./src/queue.js"
          });
        });
      }
  }

  return config;
});

Adding this will allow the queue script to be built with next build and output to .next/server/queue.js. Unfortunately the script doesn’t run with next dev, but I decided to simply run my queue jobs async on call in development and cut that part of the dev environment out, knowing I can test queues in staging and don’t have to really change that code very often anyway.

To run the queue processor, run node .nextjs/server/queue.js. The script has been processed through webpack just like any server code under Next.js.

This technique can be expanded to any scripts by adding entries like queue: "./src/queue.js" in the configuration above. I could certainly imagine adding something to detect all the scripts in a specific directory and processing them all in that way to allow for expansion of migration scripts and other useful production server-side tasks.

Love it? Hate it? Have something to say? Let me know at comments@nalanj.dev.