0

Web Fetch

Published today

Fetches the content of a web page, PDF, or file with the Apify Web Fetch Actor and returns it as Markdown, HTML, plain text, links, or raw content. It gets past bot protection and returns the content in a single step, which makes it a good fit for large language model (LLM) flows. To crawl multiple URLs or a whole website, run Website Content Crawler or Web Scraper with the Run Actor script instead.

Script apify Verified

The script

Submitted by jakub.drobnik222 Bun
Verified 3 hours ago
1
import { ApifyClient } from 'apify-client@^2.19.0';
2

3
type ApifyApiKey = {
4
  api_key: string;
5
};
6

7
type Apify = {
8
  token: string;
9
};
10

11
const createClient = (api_key?: ApifyApiKey, oauth_token?: Apify): ApifyClient => {
12
  const token = oauth_token?.token ?? api_key?.api_key;
13
  if (!token) {
14
    throw new Error('Missing Apify API key or OAuth token');
15
  }
16

17
  return new ApifyClient({
18
    token: token,
19
    requestInterceptors: [
20
      (request) => {
21
        if (!request.headers) {
22
          request.headers = {};
23
        }
24
        request.headers['x-apify-integration-platform'] = 'windmill';
25
        return request;
26
      },
27
    ],
28
  });
29
};
30

31
// constants
32
// Standby endpoint of the apify/web-fetch Actor. It answers synchronously, so
33
// unlike scrape_single_url there is no run to start and no pollRunStatus.
34
const WEB_FETCH_STANDBY_URL = 'https://web-fetch.apify.actor/';
35

36
type WebFetchFormat = 'markdown' | 'html' | 'text' | 'links' | 'raw';
37

38
const WEB_FETCH_FORMATS: WebFetchFormat[] = ['markdown', 'html', 'text', 'links', 'raw'];
39

40
// A standby cold-start plus a slow page can take far longer than the client's
41
// 360s default, so the fetch gets the same 10 min budget as the n8n node.
42
const WEB_FETCH_TIMEOUT_MS = 10 * 60 * 1000;
43

44
// Retries cover only errors of the Apify platform in front of the Actor (429, 5xx). Web Fetch's
45
// own errors are final, because the Actor already retries the fetch of the target URL.
46
const MAX_RETRIES = 3;
47
const RETRY_BACKOFF_MS = 200;
48

49
const isValidHostname = (hostname: string): boolean =>
50
  /^(?=.{1,253}$)((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$/.test(hostname);
51

52
// apify-client parses JSON by the Content-Type header, and some Web Fetch
53
// responses (e.g. 401 for a missing token) have none, so the body stays a Buffer.
54
function parseResponseBody(data: unknown): any {
55
  if (Buffer.isBuffer(data) || typeof data === 'string') {
56
    try {
57
      return JSON.parse(data.toString());
58
    } catch {
59
      return data;
60
    }
61
  }
62
  return data;
63
}
64

65
// Web Fetch errors arrive either flat ({ code, error }) or nested
66
// ({ error: { message, type } }) for platform errors such as a bad token.
67
function getWebFetchErrorMessage(status: number, body: any): string {
68
  if (body && typeof body === 'object') {
69
    if (typeof body.error === 'string') {
70
      return typeof body.code === 'string'
71
        ? `${body.error} (Web Fetch error code: ${body.code})`
72
        : body.error;
73
    }
74
    if (typeof body.error?.message === 'string') {
75
      return typeof body.error.type === 'string'
76
        ? `${body.error.message} (Web Fetch error type: ${body.error.type})`
77
        : body.error.message;
78
    }
79
  }
80
  return `Web Fetch responded with HTTP status ${status}`;
81
}
82

83
const isWebFetchError = (body: any): boolean =>
84
  !!body && typeof body === 'object' && typeof body.code === 'string' && typeof body.error === 'string';
85

86
const isRetryable = (status: number, body: any): boolean =>
87
  (status === 429 || status >= 500) && !isWebFetchError(body);
88

89
// -----------------------------------------------------------------------------
90
// main logic
91
export async function main(
92
  url: string,
93
  formats: WebFetchFormat[] = ['markdown'],
94
  headers?: Record<string, string>,
95
  api_key?: ApifyApiKey,
96
  oauth_token?: Apify,
97
) {
98
  // Reject bad URLs up front instead of leaving the validation to Web Fetch.
99
  let parsedUrl: URL | undefined;
100
  try {
101
    parsedUrl = new URL(url);
102
  } catch {
103
    // handled below
104
  }
105
  if (
106
    !parsedUrl ||
107
    (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') ||
108
    !isValidHostname(parsedUrl.hostname)
109
  ) {
110
    return {
111
      error: `Invalid URL: "${url}". Provide a full, valid URL including a domain name, e.g. https://example.com.`,
112
    };
113
  }
114

115
  // With no format selected, the formats field is left out and Web Fetch picks
116
  // one based on the content type.
117
  if (formats != null && !Array.isArray(formats)) {
118
    return { error: `Invalid formats. Allowed: ${WEB_FETCH_FORMATS.join(', ')}.` };
119
  }
120
  const requestedFormats = formats ?? [];
121
  const unknownFormats = requestedFormats.filter((format) => !WEB_FETCH_FORMATS.includes(format));
122
  if (unknownFormats.length > 0) {
123
    return {
124
      error: `Unknown format(s): ${unknownFormats.join(', ')}. Allowed: ${WEB_FETCH_FORMATS.join(', ')}.`,
125
    };
126
  }
127

128
  if (
129
    headers != null &&
130
    (typeof headers !== 'object' ||
131
      Array.isArray(headers) ||
132
      Object.values(headers).some((value) => typeof value !== 'string'))
133
  ) {
134
    return {
135
      error: 'Invalid headers. Provide an object of header names and string values, e.g. {"Accept-Language": "fr-FR"}.',
136
    };
137
  }
138

139
  // The Actor fails the whole fetch on a header without a name, so blank rows are dropped.
140
  const validHeaders = Object.fromEntries(
141
    Object.entries(headers ?? {}).filter(([name]) => name.trim()),
142
  );
143

144
  const client = createClient(api_key, oauth_token);
145

146
  try {
147
    // The client's axios instance carries the token and the integration-platform
148
    // interceptor, and it does not throw on non-2xx statuses, so Web Fetch's own
149
    // error body stays readable (ApifyApiError drops the flat { code, error } shape).
150
    // It skips the client's retry logic, so platform errors are retried here.
151
    const data = {
152
      url,
153
      ...(requestedFormats.length > 0 ? { formats: requestedFormats } : {}),
154
      ...(Object.keys(validHeaders).length > 0 ? { headers: validHeaders } : {}),
155
    };
156
    // All attempts share one time budget, so retries can't stretch the fetch past it.
157
    const deadline = Date.now() + WEB_FETCH_TIMEOUT_MS;
158
    let attempt = 0;
159
    let response;
160
    let body;
161
    while (true) {
162
      response = await client.httpClient.axios.request({
163
        url: WEB_FETCH_STANDBY_URL,
164
        method: 'POST',
165
        data,
166
        timeout: Math.max(deadline - Date.now(), 1000),
167
      });
168
      body = parseResponseBody(response.data);
169

170
      const backoff = RETRY_BACKOFF_MS * 2 ** attempt;
171
      if (
172
        response.status < 300 ||
173
        attempt >= MAX_RETRIES ||
174
        !isRetryable(response.status, body) ||
175
        Date.now() + backoff >= deadline
176
      ) {
177
        break;
178
      }
179
      await new Promise((resolve) => setTimeout(resolve, backoff));
180
      attempt += 1;
181
    }
182

183
    if (response.status >= 300) {
184
      return {
185
        error: `Failed to fetch URL. Reason: ${getWebFetchErrorMessage(response.status, body)}`,
186
      };
187
    }
188

189
    if (!body || typeof body !== 'object' || Array.isArray(body) || Buffer.isBuffer(body)) {
190
      return { error: 'Failed to fetch URL. Reason: Web Fetch returned an unexpected response.' };
191
    }
192

193
    // The envelope (url, fetch, metadata, one key per requested format) is
194
    // returned verbatim.
195
    return body;
196
  } catch (error: any) {
197
    if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
198
      return {
199
        error:
200
          `Fetching ${url} took more than ${WEB_FETCH_TIMEOUT_MS / 1000} seconds. ` +
201
          'The website may be slow or too large. Try again or use a different URL.',
202
      };
203
    }
204
    return {
205
      error: `Failed to fetch URL. Reason: ${error.message}`,
206
    };
207
  }
208
}