Skip to content

Instantly share code, notes, and snippets.

@mixdev
Forked from babldev/README.md
Created December 22, 2022 01:53
Show Gist options
  • Save mixdev/efff5f635770ac297517defc02364590 to your computer and use it in GitHub Desktop.
Save mixdev/efff5f635770ac297517defc02364590 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.ts"
}
}
// 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"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment