MondoKit GCP Tasks

Use Google Cloud Tasks to call task handler endpoints in your app.

Note: @mondokit libs all require ESM. If your project still uses CommonJS, then you can continue using our previous incarnation, gae-js, until you can make the upgrade.

Find the source code at gcp-tasks on GitHub.


npm install @mondokit/gcp-tasks

Quick Start

// Initialise tasks client (at app startup)

// Create task handlers
app.use("/tasks", appEngineTask);"/tasks/poll-status", (req, res) => res.send("OK"));"/tasks/start-job", (req, res) => res.send("OK"));

// Create service
const taskService = new TaskQueueService();

// Queue tasks
await taskService.enqueue("poll-status");
await taskService.enqueue("start-job", { body: { jobname: "job123" }});
await taskService.enqueue("start-job", { body: { jobname: "job123" }, inSeconds: 60 });


Tasks Client Provider

To have a global CloudTasksClient instance available to your entire application, initialise the tasksProvider.

// On app startup

// Elsewhere in the app
const tasksClient = tasksProvider.get();


Helper service for enqueuing tasks.

This uses the convention that tasks will be handled by a POST route of the current application, with a configured path prefix (default /tasks) and path name equal to that of the target task handler. e.g. for a target path of poll-status the target URI of the enqueued task will be POST /tasks/poll-status

When deployed to GCP the service will enqueue to a real task queue (default queue of default). Locally will invoke the target URI against the configured local target host.

Using application configuration:

const taskService = new TaskQueueService();

await taskService.enqueue("poll-status", {
  body: { jobId: "1234" },
  inSeconds: 60,

Using custom configuration:

const taskService = new TaskQueueService({
    projectId: "my-tasks-project",
    location: "my-tasks-location",
    queueName: "myqueue"

await taskService.enqueue("poll-status", {
  body: { jobId: "1234" },
  inSeconds: 60,

appEngineTask Middleware

A convenience middleware collection for your task endpoints to:

a) verify the request is a genuine Cloud Tasks request (see verifyTask middleware) and b) extend the NodeJS request timeout to 10 minutes (the default is 120s)

// Apply middleware however you normally would
app.use("/tasks", appEngineTask);

// Now any matching routes will be protected and timeout extended"/tasks/start-job", (req, res) => res.send("OK"));"/tasks/poll-status", (req, res) => res.send("OK"));

verifyTask Middleware

Use this on your task handlers to ensure they are only called by genuine Cloud Tasks requests. NOTE: This is already part of the appEngineTask middleware so no need to apply again if using that.

// Apply middleware however you normally would
app.use("/tasks", verifyTask);

// Now any matching routes will be protected"/tasks/start-job", (req, res) => res.send("OK"));"/tasks/poll-status", (req, res) => res.send("OK"));