Next.js
Background Jobs
Execute long-running tasks in the background after returning a response.
Vercel waitUntil: Using
waitUntil from @vercel/functions to process tasks outside the request lifecycle.app/api/job/route.ts
TypeScript
import { NextResponse } from 'next/server';
import { waitUntil } from '@vercel/functions';
async function performLongTask(data: any) {
// Simulate long running background task
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log('Background task completed:', data);
}
export async function POST(request: Request) {
const data = await request.json();
// The request will not wait for this to finish
waitUntil(performLongTask(data));
return NextResponse.json({ message: 'Job queued successfully!' }, { status: 202 });
}