DEV Community

Alan Johnson
Alan Johnson

Posted on • Updated on • Originally published at nalanj.dev

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.

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;
});
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
markshaw01 profile image
Mark Shaw

This didn't work w/ Next v10.0.9, but slight change did:

module.exports = {
  webpack: (config, { isServer }) => {
    if (isServer) {
      return {
        ...config,
        entry() {
          return config.entry().then(entry => {
            return Object.assign({}, entry, {
              queue: "./src/queue.ts",
            });
          });
        }
      }
    }

    return config
  },
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wchr profile image
Wachira

So am trying to load the Twitter embed script but its loaded later after the page has rendered, what should I do in order to load the script before render so that the embed is rendered as a styled component and not just text

Collapse
 
nalanj profile image
Alan Johnson

Hey - this isn't meant for adding front-end scripts, but instead for adding backend scripts that you want to build through webpack. Sorry about the ambiguity there.

Collapse
 
arthurdenner profile image
Arthur Denner

Thank you for this post, this strategy is very helpful!