Why an API Client Follows a Pagination Link to the Wrong Host

Diagnose an API pagination next link on the wrong host, test relative and absolute URLs offline, and avoid forwarding credentials to untrusted hosts.

Published
Reading time
6 min read
Why an API Client Follows a Pagination Link to the Wrong Host
On this page

An API pagination next link on the wrong host can result from a relative link being resolved against an unexpected response URL, an absolute link generated incorrectly by the API, or a redirect. The first step is to inspect both the link and the URL used as its base—without sending credentials to the resulting destination.

Key Takeaways

  • A relative continuation link needs a base URL. If the client uses the wrong base, it can select the wrong host.
  • An absolute link or a scheme-relative link such as //other-host/path can select a different host regardless of the base.
  • Validate the resolved URL against an explicit HTTPS host and port policy before making a request or attaching credentials. Repeat that validation for redirects.
  • Parsing a URL identifies its components; it does not prove that the destination or the network connection is safe.

How the base URL changes the destination

Suppose a fictional API response contains this JSON field:

{"next": "?cursor=page2"}

If the applicable base is https://api.example/v1/items?cursor=page1, resolving ?cursor=page2 keeps the host and path and replaces the query. If the base is instead https://gateway.example/v1/items?cursor=page1, the same relative link points to gateway.example.

Other link forms behave differently:

  • /v1/items?cursor=page2 replaces the path and query but keeps the base scheme and host.
  • https://api.example/v1/items?cursor=page2 is absolute and supplies its own destination.
  • //gateway.example/v1/items?cursor=page2 supplies a new host while inheriting the base scheme.

For a JSON field defined as a relative URL, the response URL is often the appropriate base, but the API's contract controls that choice. In a client that follows redirects, the response URL may be the final URL rather than the URL originally requested. Some APIs may specify a different base or use an HTTP Link header with its own context rules; do not assume every continuation mechanism is a JSON next field.

Advertisement

Diagnose the wrong host

  1. Capture the original request URL, redirect destinations, final response URL, and raw continuation value. Redact authorization headers, signed query parameters, and cursor values before sharing logs.
  2. Check whether the continuation value is absolute, scheme-relative, root-relative, or query-relative. Identify the base your client actually uses to resolve it.
  3. Compare the resulting scheme, hostname, and port with the destinations authorized for that API. A valid-looking URL can still point to an untrusted host.
  4. If the API generated an unexpected absolute URL, check its documented public endpoint and, where you operate the service, its reverse-proxy and external-URL configuration. Avoid rewriting hosts blindly: the provider may intentionally use another documented pagination host or signed URL.
  5. Review redirect behavior separately. A trusted continuation URL can redirect to a different destination; automatic redirects can hide that transition.

Check the provider's pagination contract

No API provider or documentation was supplied for this article, and official pagination documentation was not available to consult here. Before implementing a client, check your provider's official documentation for where the continuation appears, the base for relative values, permitted hosts, termination behavior, and whether continuation requests require credentials. For Link headers, use a suitable parser rather than splitting the header naively on commas.

Treat continuation URLs and cursors as potentially sensitive. Attach a credential only when the provider's contract calls for it and the destination is authorized for that credential. In particular, do not forward an API token to an unfamiliar host merely because a response supplied the URL. Some providers use signed continuation URLs instead; follow their documented authentication requirements without adding unnecessary credentials.

Run a safe, offline resolution test

The following Python standard-library example uses fictional .example hosts and makes no network requests. It models a JSON next field whose relative values are resolved against the final response URL. It accepts only HTTPS URLs on one explicitly trusted host, with no user information and no non-default port.

Save it as pagination_check.py and run python3 pagination_check.py. The assertions check the intended decisions; this example was not executed for this article.

from urllib.parse import urljoin, urlsplit

TRUSTED_HOSTS = {"api.example"}


def validate_url(url):
    if not isinstance(url, str) or not url:
        raise ValueError("URL must be a non-empty string")
    if "\\" in url or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in url):
        raise ValueError("URL contains disallowed characters")

    try:
        parts = urlsplit(url)
        host = parts.hostname
        port = parts.port
    except ValueError as exc:
        raise ValueError("Malformed URL") from exc

    if parts.scheme.lower() != "https":
        raise ValueError("HTTPS is required")
    if parts.username is not None or parts.password is not None:
        raise ValueError("URL user information is not allowed")
    if host not in TRUSTED_HOSTS or port not in (None, 443):
        raise ValueError("Untrusted host or port")
    if parts.fragment:
        raise ValueError("Fragments are not allowed")
    return url


def resolve_next(response_url, next_link):
    # Validate the base as well as the destination.
    validate_url(response_url)
    if not isinstance(next_link, str) or not next_link:
        raise ValueError("Next link must be a non-empty string")
    if "\\" in next_link or any(
        c.isspace() or ord(c) < 32 or ord(c) == 127 for c in next_link
    ):
        raise ValueError("Next link contains disallowed characters")
    return validate_url(urljoin(response_url, next_link))


base = "https://api.example/v1/items?cursor=page1"

# Fictional response fields: one relative and one absolute.
relative_response = {"next": "?cursor=page2"}
absolute_response = {"next": "https://api.example/v1/items?cursor=page2"}
expected = "https://api.example/v1/items?cursor=page2"
assert resolve_next(base, relative_response["next"]) == expected
assert resolve_next(base, absolute_response["next"]) == expected


def must_reject(response_url, next_link):
    try:
        resolve_next(response_url, next_link)
    except ValueError:
        return
    raise AssertionError("Expected the URL to be rejected")


must_reject("https://gateway.example/v1/items", "?cursor=page2")
must_reject(base, "https://gateway.example/v1/items?cursor=page2")
must_reject(base, "//gateway.example/v1/items?cursor=page2")
must_reject(base, "https://user@api.example/v1/items")
must_reject(base, "https://api.example:8443/v1/items")

The example deliberately rejects an unexpected base as well as an unexpected resolved host. Adapt the allowlist only after confirming the provider's contract. This is a URL-policy demonstration, not a complete HTTP client or a complete server-side request forgery defense.

Advertisement

For each page, resolve the continuation using the documented base and validate the destination before issuing the request. Use credentials scoped for that destination and API; never assume that a client library will safely handle authorization across hosts.

Disable automatic redirects for pagination requests when you need to enforce this policy, or use a client facility that lets you inspect each redirect before it is followed. Resolve and validate every redirect target, then make an explicit decision about credentials for the new destination. If a destination is not authorized, stop and report the mismatch rather than retrying with the token.

If your server fetches continuation URLs from an API response, host parsing alone is not enough. Account for DNS resolution and rebinding, prohibited loopback, private and link-local addresses, and redirect revalidation. Enforce network egress restrictions where possible, and set timeouts and response-size limits. A URL allowlist must be paired with controls over the actual connection; an approved hostname is not proof of a safe resolved address.

Common Mistakes

  • Resolving every relative link against the original request URL even after a redirect, without checking the API's base rules.
  • Treating //host/path as a path on the existing host.
  • Comparing raw URL strings or checking whether a trusted hostname merely appears inside the URL, rather than parsing and applying an exact host policy.
  • Passing a continuation URL straight to a client with default authorization headers or unchecked automatic redirects.
  • Logging full continuation URLs, which may expose cursors or signatures.
  • Assuming a parser, including an online parser, validates DNS, redirects, network destinations, or credential safety.

Best Practices

Keep pagination resolution, destination validation, and credential selection as separate steps. Test absolute, relative, scheme-relative, malformed, and unexpected-host links, as well as redirects, using fictional data or an authorized environment. Handle missing or invalid continuation values as errors according to the provider's contract, and set a page or request limit to avoid an accidental infinite loop.

Conclusion

When pagination reaches the wrong host, inspect the raw continuation value and the exact base used to resolve it. Then verify the provider's rules and enforce destination and credential policies on every request and redirect.

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.