FAQ: how do I issue an error HTTP response in a workflow?

Someone asked how you can issue an HTTP response that tells the client (e.g. a browser) that there was an error with the request.

The $respond() function lets you return a response in a workflow using the HTTP API trigger. When a request arrives, this lets you respond with any HTTP status code, headers, and body you’d like:

$respond({
  status: 200,
  headers: { "my-custom-header": "value" },
  body: { message: "My custom response" }, // This can be any string, object, Buffer, or Readable stream
});

You can add any HTTP status code in the status property. Depending on the specific error, you may want to issue a 400 error:

$respond({
  status: 400,
  // example. You can return a Bad Request error if the request was missing data or otherwise malformed
  body: { message: "Request body didn't contain field X. Please try again" },
});

or a 401 error for auth-related issues. For example, if you require that requests contain an API key or other secret, you can validate that in your workflow and issue a 401 error if the API key wasn’t provided or was incorrect:

$respond({
  status: 401,
  body: { message: "Invalid API key" },
});

Let us know if you have any other questions in the comments below!