How to Handle Redirects

Some programming languages have HTTP implementations that require special handling for redirects.

In response to a REST API request, the Nest API server returns a redirect. The REST client detects the redirect and requests the page that the client was redirected to. Some HTTP implementations do not forward the Authorization header to the redirected URI, and this results in a 401 Unauthorized error.

For example, suppose you ask for The server responds with a redirect to Postman or Curl pass the Authorization header to foo and then to bar. Other HTTP implementations, such as Golang's and Python's, do not automatically pass the Authorization header to the redirected URI.

How it works

The following sequence diagram shows what happens when a redirect occurs.

Redirect sequence

For comparison, here's what happens when a redirect does not occur.

No redirect sequence


Generally, it is a good coding practice to anticipate that your language's HTTP implementation might not pass the Authorization header.

Your code should prevent the automatic redirect and make the redirect call after adding the headers back.

For example, in Go, you can do this:

customClient := http.Client {
    CheckRedirect: func(redirRequest *http.Request, via []*http.Request)
    error {
        // Go's http.DefaultClient does not forward headers when a redirect 3xx
        // response is received. Thus, the header (which in this case contains the
        // Authorization token) needs to be passed forward to the redirect
        // destinations.
        redirRequest.Header = req.Header

        // Go's http.DefaultClient allows 10 redirects before returning an
        // an error. We have mimicked this default behavior.s
        if len(via) >= 10 {
            return errors.New("stopped after 10 redirects")
        return nil

For more examples, see:

Store the redirected location

It is also a best practice to store the redirected location on a per user basis. In other words, after a user signs in and a redirect is received, store the location and make all subsequent requests directly to this URI.

Storing the redirected location saves time and prevents unnecessary server load.

To learn more about how redirects relate to rate limiting, see Data Rate Limits.

Using curl to test the API

When using curl >= v7.58, you may get 401 Unauthorized errors from calls to the API that involve redirects. As of curl v7.58, custom Authorization headers are not forwarded on to the redirect URL returned by the API.

To account for this on curl >= v7.58, use the --location-trusted flag with any command line calls.