Skip to content

Instantly share code, notes, and snippets.

@babldev
Last active December 29, 2023 20:54
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save babldev/8c7b8441abcab7526786a78a73b7bebd to your computer and use it in GitHub Desktop.
Save babldev/8c7b8441abcab7526786a78a73b7bebd to your computer and use it in GitHub Desktop.
NextJS Background Task

NextJS Background Task Example

An example of how to add a background task (e.g. a queue consumer) to an existing NextJS project.

Setup

  • Add your background task file
  • Add a new worker-tsconfig.json, specifically specifying "module": "commonjs" and targeting only the worker source files.
  • Add convenience functions for building & running to package.json

Then to build once:

npm run workers-build

Or to watch source files:

npm run workers-watch

Then to run the worker:

npm run workers-start
{
"name": "nextjs-with-worker",
"source": "src/index.html",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"workers-build": "tsc --project worker-tsconfig.json",
"workers-watch": "tsc --watch --project worker-tsconfig.json",
"workers-start": "NODE_PATH=.workers/:node_modules/ node ./.workers/src/workers/task.js"
}
}
// src/workers/task.ts
import { prisma } from "src/services/PrismaService";
async function main() {
const count = await prisma.openTasks.count();
console.log(`Task count: ${count}`);
// Insert loop to consume tasks here...
}
main();
{
"compilerOptions": {
"target": "es2022",
"lib": [
"esnext"
],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"incremental": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"experimentalDecorators": true,
"outDir": "./.workers/src/",
"baseUrl": "./"
},
"include": [
"src/workers/**/*.ts"
],
"exclude": [
"node_modules"
]
}
@koolamusic
Copy link

this makes sense. thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment