Availability
This document focuses exclusively on customizing errors returned by API proxies deployed on the Gateway (data plane traffic). It does not apply to errors returned by the Tyk Dashboard API nor the Tyk Gateway API (management traffic).
Tyk Gateway Error Handling
When an error occurs during request processing, Tyk Gateway generates an HTTP error response automatically. Error conditions include authentication failures, rate limit rejections, request validation failures, and upstream connection problems, as well as error status codes (HTTP 4xx and HTTP 5xx) returned by upstream services.
The default response comprises:
- the HTTP status code defined by the triggering middleware
- a
Content-Type: application/jsonheader - an
X-Generator: tyk.ioheader - a JSON response body
- the response is provided in JSON format regardless of the
Content-Typeof the request. - the
X-Generatorheader can be suppressed by settinghide_generator_header: trueintyk.conf(or using the equivalent environment variable).
- Standardizing Format: clients expect a specific error structure, such as RFC 7807 Problem Details, that the default response does not produce.
- Gateway Migration: clients may depend on error response formats from a previous API gateway that differ from Tyk’s defaults.
- Hiding Internal Detail: default messages might expose information about your authentication mechanism, key structure, or upstream topology.
- Consistency Across APIs: upstream services may return different error formats; normalizing them at the Gateway improves the client experience.
- Per-API Requirements: different APIs published on the same Gateway may need to return different error formats or status codes for the same underlying error condition.
Customization Mechanisms
Tyk provides three mechanisms for customizing error responses. The first two are long-standing features with narrow, specific purposes. The third, introduced in Tyk v5.13.0, is a comprehensive replacement for both. Authentication Error Configuration targets specific scenarios: the HTTP status codes and message strings that Tyk returns for errors reported by the client authentication middleware, which may not suit your API contract. Its scope is intentionally narrow: it covers only the 11 built-in auth and OAuth error conditions and applies identically to all APIs on the Gateway. Response Body Overrides solve a different problem: the format of the response body. By placing Go template files in the Gateway’stemplates/ directory, you can replace the body structure (as JSON or XML) for any HTTP error status code. Templates are resolved globally based on status code and the request’s Content-Type. This applies identically to all APIs; it cannot intercept or modify error responses that originated from upstream services, and cannot differentiate between different errors that generate the same status code.
Error Overrides, introduced in Tyk v5.13.0, supersedes both. You define a set of rules against which each error is tested. Separate rules can be configured for different status codes, error type, message pattern, or upstream response content. When a rule matches, Tyk can modify any part of the response before it is returned to the client. Error Overrides works with errors generated by both Tyk and upstream services, which neither legacy mechanism can intercept.
The table below summarizes the key differences:
For new API deployments, we strongly recommend that you use Error Overrides to customize error responses. Authentication Error Configuration and Response Body Overrides remain fully supported for backward compatibility.
How the Mechanisms Interact
The three error customization mechanisms can be implemented together. We don’t recommend this, now that Error Overrides provides full customization, however it is important to understand how they will interact if more than one is deployed.- Authentication Error Configuration runs at Gateway startup, not at request time. Error Overrides and Response Body Overrides see the already-modified status codes and messages, not the original Tyk defaults.
- Error Overrides only bypasses Response Body Overrides when it provides a complete body. A rule that changes only the status code or message still falls through to the template for body formatting.
- The mechanisms can coexist. Error Overrides can be introduced incrementally: existing template files and
override_messagessettings continue to function for any error condition not covered by an override rule.
Error Overrides
Error Overrides is a powerful, declarative system that allows you to intercept errors and rewrite their HTTP status codes, headers, and bodies. It can handle both Gateway-generated errors (e.g., rate limits, auth failures) and Upstream errors (e.g.,HTTP 500 Internal Server Error returned from your backend service).
It works using a rule matching approach where each error response generated by Tyk middleware (including the proxy stage which receives the response from the upstream) is checked against a set of rules that determine the modification to be made to matching responses. If no rule matches, the response is returned to the client unaltered.
Rule Structure
Rules are organized by status code key, which can be either an exact code such as400 or a wildcard pattern such as 4xx or 5xx. Multiple rules can share the same key; they are evaluated in order and the first match wins.
Each rule has two objects:
- an optional
matchobject to specify which errors within that status code trigger the rule. - a
responseobject that defines what Tyk returns when the rule fires (in place of the original error response).
match means that the transformation in the response is applied to any error with that status code.
Matching Criteria
After the initial match on the status code key, you can refine which errors trigger the rule using thematch object. The fields available depend on whether the error was generated by Tyk Gateway or returned by an upstream service.
Matching Gateway-generated errors
- If
flagis set and matches, the rule fires. - Otherwise, if
messagePatternis set and matches the error message, the rule fires. - If a match field is set but does not match, the rule does not fire.
- If neither field is set, the rule matches any error with that status code.
Matching Upstream-generated errors
bodyField and bodyValue work together to match a specific field and value in the upstream JSON response body. bodyField is a gjson path expression identifying a field in the response; bodyValue is the expected string value for that field.
For example, given an upstream error response:
5xx Upstream Errors:
- Set
flag=URSto match upstream5xxresponses only, excluding Gateway-generated errors with the same code (such as a circuit-breaker503). - To differentiate between different upstream
5xxerrors, setbodyField/bodyValueormessagePatternto match on the response body. Note thatmessagePatternmatches on the response body for upstream errors.
4xx Upstream Errors:
flag=URSis5xx-only. There is no flag that isolates upstream4xxresponses from Gateway-generated ones with the same status code.- Use
messagePatternto differentiate by content: for Gateway errors it matches against the error message string; for upstream errors it matches against the response body. A pattern that matches the upstream response format but not Tyk’s fixed error messages effectively targets upstream responses only.
When
messagePattern or bodyField/bodyValue are used to match upstream responses, Tyk reads up to 4 KB of the response body. Content beyond 4 KB is not evaluated. If no match is found, the original response body is passed through unchanged.Response Customization
The response object defines what Tyk returns to the client when a rule matches (or fires). All fields are optional: provide any combination to achieve the override you need.statusCode: (status_code in Tyk Classic and tyk.conf)
- This is the HTTP status code to return to the client.
- Any valid HTTP status code is accepted.
- If omitted, the original error status code is preserved.
- Available as
{{.statusCode}}in Go Template Syntax used inbodyortemplate.
headers:
- A JSON object of key-value string pairs to set on the response. These are merged into the existing response headers; any key you specify sets or overrides that header while all other headers remain intact.
- If omitted, no additional headers are set.
- To remove a header, include it in
headerswith an empty value. - Note that the
X-Generatorheader cannot be removed via override rules; suppress it globally usinghide_generator_header.
message:
- The error message text.
- Available as
{{.Message}}in Go Template Syntax used inbodyortemplate. - If omitted,
{{.Message}}resolves to an empty string in thebodyortemplate.
body:
- The response body, written verbatim to the client.
- Can be a static string or a Go template string (see Go Template Syntax).
- When
bodyis provided, the legacy template system is bypassed entirely. - If
bodyis set,templateis ignored.
template:
- The base filename (without extension) of a file in the Gateway’s
templates/directory. - The file content is used as the response body, written verbatim to the client.
- Tyk appends
.jsonor.xmlto the base filename based on theContent-Typeof the original request.- For example,
"my_error"resolves totemplates/my_error.jsonfor JSON requests andtemplates/my_error.xmlfor XML requests.
- For example,
- Use
templateas an alternative tobodywhen the template body is large or shared across multiple rules.
Partial Override
If neitherbody nor template is set, the rule is a partial override as it does not contain any response body content. Tyk applies the statusCode and message from the matching rule. Use this when you want to change the status code or message while retaining the existing body format.
A partial override will pass through the legacy template system, which may format the response body. Be careful if you have both Error Overrides and Response Body Overrides configured to avoid unintended behavior.
XML Clients
Inlinebody overrides are written verbatim regardless of the Content-Type of the original request. To serve XML to XML clients using an inline body, ensure that the body contains XML formatted content. If using template, then ensure you provide a .xml file variant, as Tyk will select that given Content-Type: "application/xml" in the request.
Go Template Syntax
The files referenced by the
template field are distinct from the Response Body Overrides legacy system. Both reside in the Gateway’s templates/ directory, but Error Override template files are referenced explicitly by name in a rule and have access to the variables listed below. Legacy template files are selected automatically by filename convention and only have access to {{.Message}}.body field and the files referenced by the template field support Go template syntax. The variables available in error override templates are specific to the error context and are listed below.
The following variables are always available:
{{.StatusCode}}: The HTTP status code being returned.{{.Message}}: The error message text.
response.statusCode or response.message are declared in the override rule, these will be applied prior to the template being resolved and so the override value will be applied to the template, not the value from the original error message.
Some errors inject additional variables:
{{.InvalidParams}}: A string describing the specific validation failure. Only available whenflag=BIV(see Request Validation). Example:"body.age must be a positive integer".
Configuration
Error Overrides can be configured in two layers:- Gateway-level configuration is applied to all APIs deployed on the Gateway
- API-level configuration applies to a specific API and is evaluated first
Gateway Level
Configure overrides that apply to all APIs deployed on the Gateway using theerror_overrides object in the Gateway config (tyk.conf or equivalent environment variables):
API Level
Configure overrides for a specific API in theerrorOverrides section of the Tyk Vendor Extension:
"enabled": false to disable API-level overrides without removing the configuration.
If using Tyk Classic APIs, configure overrides at the top level of the API definition:
"error_overrides_disabled": true to disable API-level overrides without removing the configuration.
Flag Reference
The following flags classify errors generated by Tyk Gateway and can be used in theflag field of a match object. For intercepting upstream error responses, see Upstream Error Responses.
Authentication and Authorization Errors
Request Validation Errors
Rate Limiting and Quota Errors
Upstream Connectivity Errors
TLS Errors
Upstream Error Responses
Upstream5xx error responses carry the URS flag. Use flag=URS in a match rule to restrict it to upstream responses only, preventing it from also matching gateway-generated errors with the same status code.
Response Body Overrides
This is a legacy feature. For new implementations, we recommend using Error Overrides instead.
templates/ directory in its local filesystem. Tyk selects a file based on the HTTP status code and the request’s Content-Type (for example, error_500.json or error_500.xml), falling back to a generic error.json or error.xml if no status code-specific file exists.
The content of the selected file is used to replace the body of the error response. Go template syntax is available, but only the {{.Message}} variable is supported, which contains the error message text.
Note the following limitations on the scope of this feature:
- Gateway-Level Scope: The same customized response bodies are applied for all APIs on the Gateway.
- Upstream Errors: This method cannot intercept upstream errors.
- Status Code Scope: There is no way to differentiate between different errors that share the same status code.
HTTP 404Limitation: Response Body Overrides cannot be used to customize the body ofHTTP 404responses.- Response Body Only: This method does not enable customization of status code, error message or headers.
Authentication Error Configuration
This is a legacy feature. For new implementations, we recommend using Error Overrides instead.
override_messages configuration in tyk.conf. It is provided for cases where your API contract requires specific status codes or messages for auth failures that differ from Tyk’s defaults.
Specify the message ID in the override_messages object in tyk.conf and provide a code, message, or both:
- Limited Scope: This method only works for specific auth-related errors.
- Gateway-Level Scope: The same responses are applied for all APIs on the Gateway.
- Limited Customization: This method does not enable customization of response body or headers.
Other Error Configurations
Tyk offers error configurations within certain middleware:- Request Validation: When using Request Validation middleware, the HTTP status code returned in case of validation failure can be configured in the API definition.
- HMAC Signature Validation: The HMAC signature authentication middleware exposes fields that set the HTTP status code and error message returned when signature validation fails.
- Custom Plugins: JavaScript plugins and Rich Plugins can use the Return Overrides mechanism to halt middleware execution and return a custom HTTP response directly to the client. Go plugins can write directly to the
http.ResponseWriterto terminate the request and return a fully custom status code, headers, and body. - Virtual Endpoints: Virtual endpoints execute a JavaScript function that returns a fully custom response (status code, headers, and body) via the
TykJsResponse()function.