Redirecting APIs in Tyk is a common task that provides benefits like domain aliasing, keeping links alive, temporary responses to unsafe and long requests. These benefits greatly enhances the user experience by ensuring seamless navigation and efficient routing of requests. Whether you need to redirect traffic from an outdated endpoint to a new one or manage URL changes more effectively, Tyk provides the tools to accomplish this.
This guide will walk you through the steps to set up a redirect in Tyk, ensuring that your API traffic is efficiently managed and directed to the correct endpoints. We'll cover:
- Different approaches to achieve redirects
- Configuration examples with code snippets
- Limitations and stop gaps
Straightforward redirection via inbuilt middleware
This approach leverages Tyk's built-in middleware functionality to return a redirection message/status code and the new location header pointing to the target URL. The combination of relative path matching, mock response middleware and a location header makes it possible to generate a simple redirect response. Here is a sample below
Mock response middleware via the endpoint designer in the dashboard
A request to this endpoint gets redirected to the Google search website via a browser. However, a 301 Moved Permanently response is generated via an API client such as curl.
Result of a curl request to the endpoint
curl -X GET -I http://localhost:8080/redirect-api/fulcrum/next
HTTP/1.1 301 Moved Permanently
Location: http://google.com
Date: Thu, 11 May 2023 13:05:43 GMT
Content-Length: 0
You can use the location option (-L ) within curl to follow through to the redirected URL.
curl -X GET -L http://localhost:8080/redirect-api/fulcrum/next
Lack of authentication, access control, logs and analytics record
Using mock middleware ignores authentication, access control, other Tyk middleware except version check and prevents the generation of gateway logs. Consequently, neither the gateway nor the pump will produce or purge any analytics record. We recommend using custom code for handling redirection if authentication, access control, inbuilt middleware, logging and/or analytics is crucial for your needs. This ensures that all relevant data is properly collected and available for analysis.
Enhanced redirection via custom code
This method offers more granular control over the redirect logic but requires developing custom code. The options here range from utilising virtual endpoint to any type of language supported by custom plugins. Your implementation may be as simple as inputting static values or dynamic as using parts of the URL path, query string or fragment component in the redirect location.
Simple virtual endpoint example
A snippet of a custom redirect virtual endpoint plugin
function simpleVirtualEndpointRedirect(request, session, config) {
log("Started: simpleVirtualEndpointRedirect")
// Log request [object](https://tyk.io/docs/plugins/supported-languages/
javascript-middleware/middleware-scripting-guide/#the-request-object)
log("Request: " + JSON.stringify(request))
/*
* Copy and paste snippet logic below
*/
var headers = {
"Content-Type" : "text/html",
"Location": redirectURL
};
var responseObject = {
Code: 301,
Headers: headers
}
log("Finished: simpleVirtualEndpointRedirect")
return TykJsResponse(responseObject, session.meta_data)
}
URL path logic snippet
// Log URL path
log("URL Path: " + request.URL)
// Query params example
redirectURL = "https://httpbin.org/anything/" + request.URL
Query param logic snippet
// Log query param details.
log("Query params: " + JSON.stringify(request.Params))
// Query params example
redirectURL = "https://google.com/search?q=" + request.Params["url"]
Headers logic snippet
// Log header details.
log("Query params: " + JSON.stringify(request.Headers))
// Query params example
redirectURL = "https://google.com/search?q=" + request.Headers["url"]
Key Session logic snippet
// Log session [object](https://tyk.io/docs/plugins/supported-languages/javascript-middleware/middleware-scripting-guide/#the-session-object).
log("Query params: " + JSON.stringify(session))
// Key session example
redirectURL = "https://google.com/search?q=" + session.url
Config data logic snippet
// Log config [object](https://tyk.io/docs/plugins/supported-languages/javascript-middleware/middleware-scripting-guide/#the-config-object).
log("Query params: " + JSON.stringify(config))
// config data example
redirectURL = "https://google.com/search?q=" + config.config_data.url
Advanced virtual endpoint example
A snippet of a custom redirect virtual endpoint plugin
function enhancedVirtualEndpointRedirect(request, session, config){
log("Started: enhancedVirtualEndpointRedirect");
// Compose the redirect URL or perform any custom transformations
var redirectURL = custom_code
//
var responseObject = redirectURL(302, decodeURIComponent(redirectURL))
log("Finished: enhancedVirtualEndpointRedirect");
return TykJsResponse(responseObject, session.meta_data)
}
function redirectURL(statusCodeInt, urlString) {
switch (statusCodeInt) {
case 301:
case 302:
case 303:
case 307:
case 308:
break:
default:
var message = "Status code supplied is not used for redirection. Please visit https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location for more information about using the Location header"
log("Status code validation error: " + message)
break;
}
var response = {
Code: statusCodeInt,
Headers: {
"Location": urlString
}
return response
}
TykMakeHttpRequest cannot avoid following redirects
Virtual endpoints (and possibly JavaScript) currently have no flag to disable or avoid redirect follow-through (location forwarding) when TykMakeHttpRequest
is triggered. As an alternative, you can use Golang Virtual Endpoints or compose your custom plugins within the pre-request plugin lifecycle (to bypass the authentication phase) or within the post middleware phase (to take advantage of authentication and request transformation middlewares).
Comments
0 comments
Please sign in to leave a comment.