Search code examples
javascriptnode.jsnext.jsbullmq

How do I get a js file to run in Next.js backend?


I have a few lines of code in a file that I use to instantiate a worker for bullmq. It works independently from the rest of the server so Next.js never runs it since it's not imported anywhere.

e.g. I have the following in a standalone file that I want the server to run.

const emailWorker = new Worker("emailSchedule", emailWorkerJob, {
  connection: redisConfiguration
});

I ended up exporting emailWorker and importing it into some file that gets called by an API to force the code run. Is there another solution?


Solution

  • I was able to fix this by setting autorun: false in the worker, then exporting to one of the file that gets loaded and calling emailWorker.run()

    emailWorker.js

    const emailWorker = new Worker("emailSchedule", emailWorkerJob, {
      connection: <<redis connection>>,
      autorun: false
    });
    
    export default emailWorker;
    

    bullmq.js

    import emailWorker from "./workers/emailWorker"
    ...
    emailWorker.run()