Feature request: Conditional `followRedirects` in httpClientLib

I would like to be get the option to pass a callback (predicate) to the followRedirects parameter in httpLib.request().

The callback will take the location of a redirect, and return a boolean to decide if the redirect should be followed or not.

const res = httpLib.request({
   ...
   followRedirects: (location) => {
      return location.indexOf("https://mydomain.com") !== -1
   }
})

The TypeScript type would be:

type followRedirects = boolean | (location: string) => boolean;

I hacket myself a version of this if anyone is interested

import {request} from "/lib/http-client"
import type {HttpRequestParams, HttpResponse} from "enonic-types/http";

export function httpRequest(params: RequestParams): HttpResponse {
  const res = request({
    ...params,
    followRedirects: typeof params.followRedirects === "boolean"
      ? params.followRedirects
      : false
  });
  
  if (isRedirect(res)
    && res.headers.location
    && typeof params.followRedirects === "function"
    && params.followRedirects(res.headers.location)
  ) {
    return httpRequest({
      ...params,
      url: res.headers.location
    })
  } else {
    return res;
  }
}

function isRedirect(res: HttpResponse): boolean {
  return res.status >= 300 && res.status < 400;
}

export type RequestParams = Omit<HttpRequestParams, 'followRedirects'> & {
  followRedirects: boolean | ((location: string) => boolean);
}

I had a look at the code in http-client-lib, and I’m guessing this library isn’t actually the right place to implement a solution to my problem.

The correct place would be to add the functionality to the OkHttp library. So I opened an issue on their Github, and I invite you to go there and like the issue!

Thanks!
– Tom

1 Like

Sweet - but remember you need to handle “loops” in these redirects as well :slight_smile:

Hmm… Looking at that topic, it seems they basically recommend you to implement this yourself?

As well as OkHttp developers, I’d say it is a very niche functionality.
You usually do want to follow redirects (with some cautions). If you don’t - turn it of and do what you want with the response.

I don’t think this functionality (conditional follow redirects) exists in any http client.

Yea, I think this might be true.

I’ve only hit these use cases because I’m doing some slightly weird stuff to get my headless project working with previews in Content Studio.


That said…

What is the chance to get NetworkInterceptor and/or Interceptor exposed in http-client-lib?

Depends, on how much more interest will be in having interceptors.
For your specific case you won’t benefit forum having interceptors - your code would remain almost the same.

Yes, I guess. I just don’t feel to good about that code above, and I was hoping to make something a bit more clean.

But I guess you are correct in that using Interceptors will still be a bit hacky.

Feel free to close this thread