Skip to main content

Custom Response

Overview

The Custom Response policy action returns a hard-coded response back to the client that made a request to your endpoint.

Example

Traffic Policy for returning an inbound json error message with custom headers.

# snippet
---
actions:
- type: "custom-response"
config:
status_code: 400
content: "{\"error\":{\"message\":\"Bad Request\",\"time\":\"${time.now}\"}}"
headers:
content-type: "application/json"
x-custom-header: "custom-value"
x-template-example: "started at ${conn.ts.start}"

Request:

curl https://example.ngrok.app/api/example

Result:

< HTTP/2 400
< content-type: application/json
< x-custom-header: custom-value
< x-template-example: started at 2024-06-24T15:30:00Z

{
error: {
message: "Bad Request",
time: "2024-06-24T15:30:00Z"
}
}

Behavior

When executed as an inbound policy, this action bypasses the upstream server and immediately returns to the caller with the configured response. When executed as an outbound policy, the response from the upstream server is overwritten with the configured response.

If this action is executed, no further actions in the traffic policy will be executed.

Reference

Supported Directions

  • Inbound
  • Outbound

Configuration

Type
custom-response
Parameter Description
status_codeintThe status code of the response.
contentstringThe body of the response. Supports interpolating the results of cel expressions.
headersMap<string, string>Headers to be added to the response. If content-type is not included in headers, this action will attempt to infer the correct content-type.

Templating Syntax

The results of CEL expressions can be interpolated into your policy's config using ngrok's ${} templating syntax. For a complete list of available variables and functions or to see a more detailed explanation, checkout the docs.

More Examples

Json response body with cel expressions
# snippet
---
actions:
- type: "custom-response"
config:
status_code: 200
content: "{\"connection-start\":\"${conn.ts.start}\"}"
headers:
content-type: "application/json"

Request:

curl https://example.ngrok.app/api/example

Result:

< HTTP/2 200
< content-type: application/json

{
"connection-start": "2024-06-24T15:30:00Z"
}

Multiple inline expressions with a plain text response body
# snippet
---
actions:
- type: "custom-response"
config:
status_code: 418
content: "connection began at ${conn.ts.start}, now ${timestamp(time.now)}"
headers:
content-type: "text/plain"

Request:

curl https://example.ngrok.app/api/example

Result:

< HTTP/2 200
< content-type: text/plain

"connection began at 2024-06-24T15:30:00Z, now 2024-06-24T16:30:00Z"