Alex W.'s Blog

How to implement max download size with `got`

The sindresorhus/got documentation provides a hooks based approach which can be found at Advanced Creation: Limiting Download & Upload Size.

You can also use to implement this functionality in a manner that avoids any response body download if the content-length header indicates that the download will be too large (the sample in the official docs only terminates the download after the limit has already been downloaded):

const limitResponseSize = got.extend({
  handlers: [
    (options: NormalizedOptions & { maxResponseSize?: number }, next) => {
      let promiseOrStream = next(options)
      if (typeof options.maxResponseSize === "number") {
        promiseOrStream.on("downloadProgress", (progress: Progress) => {
          const size = Math.max( ?? 0, progress.transferred)
          if (size > options.maxResponseSize!) {
              `Response size of ${size} exceeded limit of ${options.maxResponseSize}`
      return promiseOrStream

Unfortunately the got type system doesn’t provide a convenient way to expose to callers that the options parameter has been expanded to support an additional type so you will have to override the type complaint at the call site.

Written by Alex Wendland, who is currently exploring fintech at Pinwheel. Here's a Twitter handle, a GitHub, some LinkedIn, ol' Facebook, or a hip Instagram if you're interested.