Twitter (X) and Puppeteer in 2026: What a Node.js Scraper Runs Into, and the API Route

By TwitterAPI.io Team•15 min read
Diagram comparing two ways to get Twitter (X) data from Node.js. Orange Puppeteer route: npm i puppeteer downloads 170 to 282 MB of Chrome for Testing, launch and goto x.com, the login wall since June 30, 2023, a logged-in session that acts as an account X can lock, parsing the DOM or internal /i/api responses, and X's terms requiring prior written consent for scraping. Blue REST route: an X-API-Key header with no X account, GET /twitter/tweet/advanced_search, a JSON page of 20 tweets with has_next_page, a next_cursor loop, typed fields such as likeCount, viewCount, author and media, billed at 15 credits per post. Footer: 26 requests, 520 unique posts, 0 duplicates, $0.078 versus $2.60 at the official X API rate.
Two pipelines for the same job. Diagram; the footer numbers come from the study below, collected in 2026.
TL;DR
  • What Puppeteer is: an open-source Node.js library for controlling Chrome from code. npm i puppeteer downloads Chrome for Testing (about 170 MB on macOS, 282 MB on Linux) plus chrome-headless-shell into ~/.cache/puppeteer; version 26.0.0 requires Node 22.12 or newer.
  • What it meets on x.com: the login wall in place since June 30, 2023, so useful pages need a logged-in session that acts as a real account (X can rate-limit, lock or suspend it); data that arrives from undocumented internal endpoints under /i/api/; and markup that changes without notice.
  • What X's rules say: the Terms of Service (effective October 9, 2026) prohibit "crawling or scraping the Services in any form, for any purpose without our prior written consent", with liquidated damages of $15,000 per 1,000,000 posts above 1,000,000 in 24 hours; x.com/robots.txt says Disallow: / for User-agent: *.
  • The Node.js API route: fetch GET /twitter/tweet/advanced_search with X-API-Key, read tweets[], follow next_cursor while has_next_page is true. No browser, no X account, no HTML parsing.
  • Measured: a #javascript Latest search returned 520 unique posts in 26 requests (20 per page, 0 duplicates) covering 4.5 days; 66.7% carried media and 100% had integer like, repost, reply, quote, view and bookmark counts.
  • Cost: 7,800 credits = $0.078 for the 520 posts ($0.15 per 1,000), against $2.60 at the official X API pay-per-usage rate of $0.005 per post read, about 33x more.

This page is the Node.js and Puppeteer version of a question we already answered for Python: our Twitter Selenium guide covers what a Selenium-driven browser gets from x.com. Here the stack is JavaScript end to end, so the questions are Puppeteer-specific: what npm i puppeteer installs, how the two Puppeteer patterns people reach for (reading the rendered DOM, and listening to the page's network responses) behave on a site that hides its content behind a login, what X's terms and robots.txt say, and what the same job looks like as a plain fetch loop in Node. A Playwright version of this comparison is a separate guide.

We did not point Puppeteer at x.com for this page. Driving x.com with a browser means either working with a logged-out view that X restricts or logging in with an account, and X's terms prohibit scraping without written consent; neither is something we will demonstrate. Everything about Puppeteer here comes from its own documentation at pptr.dev and its npm registry entry, and everything about X from its terms, its robots.txt, its developer docs and its owner's public statements, all checked this year.

The data half of the page is first-hand. We ran the job people usually try with Puppeteer, collect a few hundred posts for one hashtag, through the REST API from a rate-limited client: 26 requests, 520 posts of #javascript, timed and checked field by field. The numbers in the tables and charts below come from that run, collected in 2026.

Posts collected for one hashtag, no browser

520 unique #javascript posts in 26 requests, 0 duplicates, every engagement count an integer: $0.078 at $0.15 per 1,000 posts vs $2.60 at the official X API rate (collected in 2026).

01 — Section

What Puppeteer is and what npm i puppeteer installs

Puppeteer is an open-source Node.js library that controls a Chrome browser programmatically. You launch a browser, open pages, click, type, wait for elements and read the result, the same as a person would, from JavaScript. It is very widely used: the npm registry counted about 14.6 million downloads of the puppeteer package in one recent week, for testing, PDF generation, screenshots and crawling.

What the install pulls in. Per the installation guide on pptr.dev, npm i puppeteer downloads a recent build of Chrome for Testing (about 170 MB on macOS, 282 MB on Linux, 280 MB on Windows) and, since version 21.6.0, a chrome-headless-shell binary, into $HOME/.cache/puppeteer. The puppeteer-core package is the same library without a browser download; you pass an executablePath or a channel yourself, which is the usual choice for connecting to a remote browser.

Version and runtime. The npm registry lists 26.0.0 as the latest release at the time of writing, declaring node >=22.12.0 in its engines field. Older tutorials that use page.setCookie() are out of date: the API reference now marks the page-level cookie API obsolete and points to Browser.setCookie() or BrowserContext.setCookie().

Two ways to get data out. Puppeteer offers two patterns, and every Twitter Puppeteer tutorial uses one or both. The first reads the rendered page: page.locator() (which the docs call "the recommended way to select an element and interact with it", because it waits for the element automatically) or page.$$eval(), which runs a function over every element matching a selector. The second listens to the network: page.on('response', ...) fires for every response the page receives, and HTTPResponse.json() returns the parsed body (it throws if the body is not valid JSON). page.waitForResponse() waits for one matching response, with a 30-second default timeout.

The example below shows both patterns as the docs describe them, on a placeholder URL. It is a general Puppeteer recipe for an app you own or have permission to automate, not an x.com scraper.

javascript
// Generic Puppeteer pattern from pptr.dev, shown on a placeholder URL.
// Use it only on sites you own or have written permission to automate.
//   npm i puppeteer   (downloads Chrome for Testing; Puppeteer 26 needs Node >= 22.12)
import puppeteer from "puppeteer";

const browser = await puppeteer.launch();            // headless by default
const page = await browser.newPage();

// Pattern 1: listen to network responses and keep the JSON ones
const payloads = [];
page.on("response", async (response) => {
  const type = response.headers()["content-type"] ?? "";
  if (!type.includes("application/json")) return;
  try {
    payloads.push({ url: response.url(), body: await response.json() });
  } catch {
    // json() throws when the body is not parsable (redirects, empty bodies)
  }
});

// Pattern 2: wait for one specific response (default timeout 30 s)
const apiResponse = page.waitForResponse(
  (r) => r.url().includes("/api/items") && r.status() === 200,
);
await page.goto("https://your-own-app.example/items");
const data = await (await apiResponse).json();

// Pattern 3: read rendered elements with a locator or $$eval
const titles = await page.$$eval("[data-item-title]", (els) => els.map((e) => e.textContent));

console.log(payloads.length, Object.keys(data), titles.length);
await browser.close();
02 — Section

What a Puppeteer script runs into on x.com

The login wall. On June 30, 2023 X stopped showing timelines to logged-out visitors. Elon Musk replied the same day that it was a "Temporary emergency measure. We were getting data pillaged so much that it was degrading service for normal users!" (we fetched that reply by ID for this page). The measure stayed. A logged-out page load in our Selenium guide showed only the top of a public profile and a "Log in or sign up for X" prompt. A Puppeteer script sees the same thing, because Puppeteer is a real Chrome: there is no Puppeteer-specific view of x.com.

A logged-in session is an account. Tutorials get past the wall by logging in inside Puppeteer or by loading saved cookies with browser.setCookie(). Either way, every request the script makes is made as that X account. X can rate-limit, lock or suspend it, and the session can expire and need a fresh login. Scripts that log in often report X's "This request looks like it might be automated" message (error 226), which is X telling you the account's behavior looks automated; treat it as a signal to stop. We do not give advice on making a script look less automated.

Internal endpoints, not a public API. The response-listening pattern works because x.com's front end loads posts as JSON from undocumented endpoints under x.com/i/api/graphql/..., operations with names such as UserTweets and SearchTimeline (our Twitter GraphQL API explainer covers how those operations, their query IDs and headers keep changing). Capturing them with page.on('response') saves you HTML parsing, but you are still reading an internal contract that X changes without notice, through a logged-in account.

Rendering and selectors. The DOM pattern has its own costs. Timelines render client-side and load more posts as you scroll, so a script has to scroll, wait and de-duplicate, and it keys on attributes like data-testid that belong to X's front end and change without notice.

What you needPuppeteer on x.comREST API from Node
Installpuppeteer plus 170 to 282 MB of Chrome for Testingnothing beyond Node 18+ (fetch is built in)
Credentialsa logged-in X account (session cookies)an API key in the X-API-Key header; no X account
Data sourcerendered DOM or undocumented /i/api/ responsesdocumented JSON: tweets[], has_next_page, next_cursor
Paginationscroll, wait, de-duplicatepass next_cursor back as cursor
What can break itlogin checkpoints, account locks, front-end changesyour key, your rate limit, your credit balance
03 — Section

What X's Terms of Service and robots.txt say about browser scraping

Two primary documents apply to any Twitter Puppeteer project, and both are short on this point.

Terms of Service. The current X Terms (effective October 9, 2026) list among misuses of the service: "crawling or scraping the Services in any form, for any purpose without our prior written consent is expressly prohibited". The same terms set liquidated damages of $15,000 per 1,000,000 posts when someone requests, views or accesses more than 1,000,000 posts in any 24-hour period (EUR 15,000 in the EU and UK version). A headless Chrome is not exempt because it is a real browser; the clause is about the activity, not the tool.

robots.txt. x.com/robots.txt has a group for named search-engine crawlers (Googlebot and Bingbot get specific Allow and Disallow rules) and then, for every other user agent, User-agent: * followed by Disallow: /, with a Crawl-delay: 1 line further down. A Puppeteer crawler is an "other" user agent.

Logged-in sessions. When the script uses your account, the account holder is the one agreeing to those terms. That is why the risk in the previous section (rate limits, locks, suspension) lands on the account, not on the script.

None of this is legal advice. It is what the documents say, and it is the reason this page does not include a working x.com scraper. If you need the data, the two documented routes are X's own API and a third-party API that returns the same public posts as JSON, which is the rest of this page.

04 — Section

The same job in Node.js: one fetch call per page

The typical Twitter Puppeteer tutorial collects posts for a search or hashtag and writes them to a file. Here is that job without a browser. /twitter/tweet/advanced_search takes query (the same operators as X's advanced search: #tag, from:, lang:, min_faves:, since_time: and so on) and queryType (Latest or Top). Each response is a top-level tweets array of up to 20 posts, plus has_next_page and next_cursor; pass the cursor back as cursor to get the next page.

Fields arrive typed. Each post object has id, url, text, createdAt (a string like Thu Oct 16 12:34:56 +0000 2026, which new Date() parses), lang, the six counts likeCount, retweetCount, replyCount, quoteCount, viewCount, bookmarkCount as integers, isReply, quoted_tweet, entities (hashtags, urls, user_mentions), extendedEntities.media[] with type photo, video or animated_gif, and an author object with userName, followers and isBlueVerified. There is no "1.2K" to parse back into a number, which is where DOM scrapers usually lose precision.

Pacing. Accounts that have not paid yet are limited to 0.2 requests per second, so use a fixed 5-second pause between pages; after the first payment the limit is 20 requests per second (50 on Scale, 500 on Business). Use a fixed pause and back off on HTTP 429; there is nothing to randomize.

Errors. A missing or invalid parameter returns HTTP 400 with the explanation in detail; other API errors come back as status: "error" with the text in msg. The full script at the end of the page handles both, plus retries on 429 and 5xx.

The short version below is enough to replace a Puppeteer hashtag scraper. Run it with node hashtag-search.mjs "#javascript" 500.

javascript
// hashtag-search.mjs - collect about 500 posts for a hashtag as JSON with Node 18+ fetch.
//   TWITTERAPI_IO_API_KEY=... node hashtag-search.mjs "#javascript" 500
import fs from "node:fs";

const API = "https://api.twitterapi.io";
const [query = "#javascript", target = "500"] = process.argv.slice(2);
const PAUSE_MS = 250; // fixed pacing; use 5000 before your first payment (0.2 requests/s)
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const seen = new Set();
const rows = [];
let cursor = "";

while (rows.length < Number(target)) {
  const params = new URLSearchParams({ query, queryType: "Latest" });
  if (cursor) params.set("cursor", cursor);
  const res = await fetch(`${API}/twitter/tweet/advanced_search?${params}`, {
    headers: { "X-API-Key": process.env.TWITTERAPI_IO_API_KEY },
  });
  if (res.status === 429) { await sleep(5000); continue; } // over your rate limit: wait, retry
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
  const body = await res.json();
  for (const t of body.tweets ?? []) {
    if (seen.has(t.id)) continue;
    seen.add(t.id);
    rows.push({
      id: t.id,
      url: t.url,
      createdAt: t.createdAt, // "Thu Oct 16 12:34:56 +0000 2026", not ISO 8601
      text: t.text,
      lang: t.lang,
      likes: t.likeCount,
      reposts: t.retweetCount,
      replies: t.replyCount,
      quotes: t.quoteCount,
      views: t.viewCount,
      bookmarks: t.bookmarkCount,
      author: t.author?.userName,
      authorFollowers: t.author?.followers,
      hashtags: (t.entities?.hashtags ?? []).map((h) => h.text),
      media: (t.extendedEntities?.media ?? []).map((m) => m.type),
    });
  }
  if (!body.has_next_page || !body.next_cursor) break;
  cursor = body.next_cursor;
  await sleep(PAUSE_MS);
}

fs.writeFileSync("posts.jsonl", rows.map((r) => JSON.stringify(r)).join("\n") + "\n");
console.error(`${rows.length} posts written to posts.jsonl`);
05 — Section

Our study: 520 #javascript posts in 26 requests

We ran exactly that loop for #javascript with queryType=Latest, through our own rate-limited study client, until we had a little over 500 posts. These are the numbers a Puppeteer scraper would have had to reproduce by scrolling a logged-in search page.

MeasureResult
Requests26
Posts returned520 (20 on every page)
Duplicate IDs across pages0
has_next_page on the last pagetrue (more results were available)
Time span covered108.5 hours (4.5 days), about 4.8 posts an hour
Distinct authors238; the 5 busiest wrote 35.4% of posts
Wall time96.5 s, 3.71 s per request on a shared client
Cost7,800 credits = $0.078

Every page was full and nothing repeated. All 26 pages held 20 posts and the cursor never handed back a post we already had, so the de-duplication set in the script is a safety net rather than a necessity. The last page still reported has_next_page: true; we stopped because we had our sample, not because the search ran dry.

Wall time is mostly queueing. 96.5 seconds for 26 requests is 3.71 seconds per page, but our study client shares a single 5-requests-per-second budget with several other jobs and spaces every call through a lock, so that figure is an upper bound for this setup rather than the API's response time. At the 0.2 requests per second limit that applies before a first payment, the same 26 pages take at least 130 seconds of pacing.

A hashtag is not a random sample of X. #javascript produced about 4.8 posts an hour, and the five busiest accounts wrote 35.4% of them. 95.0% of posts carried other hashtags too (the top co-occurring ones were #100DaysOfCode, #Python, #coding and #programming), a pattern consistent with accounts that post hashtag-heavy promotional content on a schedule. If you are building a dataset, filter with operators such as min_faves: or -filter:links in the query rather than after collection, because you pay for what is returned.

Horizontal bar chart of what 520 #javascript posts carried as structured JSON in 26 requests: engagement counts as integers 100%, other hashtags besides #javascript 95.0%, media 66.7%, a link 60.2%, text longer than 280 characters 35.8%, mentions an account 8.3%, replies 2.9%, quotes 2.7%.
Share of 520 #javascript posts with each field populated, read directly from the API response, collected in 2026.
06 — Section

What a DOM scraper sees vs what the JSON gives

A Puppeteer DOM scraper reads what x.com renders for a person: abbreviated counts, relative timestamps and whatever the page chose to show. The JSON carries the underlying values. This table maps the usual scraper targets to the API fields we read in the study.

Scraper target on the pageAPI fieldIn our sample
Like count (rendered as "1.2K")likeCount (integer)median 1, 90th percentile 13, 42.9% zero
View countviewCount (integer)median 71, 90th percentile 484
Reposts and repliesretweetCount, replyCount63.8% and 82.1% zero
Bookmarks (not shown on others' posts)bookmarkCount90th percentile 4
Images and videoextendedEntities.media[].type347 posts with media; 523 photos, 61 videos, 7 GIFs
"Show more" on long postsfull text35.8% over 280 characters, median 262
Languagelang81.2% en, 7.5% ja
Timestamp ("2h")createdAtfull date, time and offset

Small numbers, many zeros. The median #javascript post had 1 like and 71 views; 96.7% had no quotes and 82.1% no replies. That matters for scrapers in a quiet way: a DOM script that reads an empty counter cannot tell "zero" from "not rendered yet", while the API returns 0 explicitly. Only 0.8% of posts had a viewCount of zero.

Author data comes along. Each post includes its author's profile summary, so the 238 authors in the sample cost nothing extra to describe in aggregate: median 89 followers, 90th percentile 4,799, and 19.3% with a paid blue check. With Puppeteer that would mean visiting each profile page.

Grouped bar chart of engagement on 520 #javascript posts, median versus 90th percentile: likeCount 1 and 13, retweetCount 0 and 4, replyCount 0 and 1, quoteCount 0 and 0, bookmarkCount 0 and 4; viewCount on its own scale, 71 and 484. Labels show the share of zero values per field.
Median and 90th-percentile engagement per post across 520 #javascript posts, collected in 2026.
07 — Section

Cost: Puppeteer is free to run, the data is not

Puppeteer itself is open source and costs nothing. What a Puppeteer scraper of x.com really spends is an X account, the machine time of a Chrome per worker, and the maintenance hours each time the front end changes, plus the terms risk described above. The two documented routes have a price list instead.

RoutePrice per post read520 posts1,000 postsNeeds
Official X API, pay-per-usage$0.005$2.60$5.00a developer account and app; capped at 3M post reads a month
twitterapi.io advanced_search15 credits ($0.00015)$0.078$0.15an API key; no X account
Puppeteer on x.comno price listan X account, Chrome per workersamewritten consent under X's terms

About 33x per 1,000 posts. The official X API's rate card (docs.x.com/x-api/getting-started/pricing) is $0.005 per post read, $0.010 per user read, and pay-per-usage is capped at 3 million post reads per billing cycle, with Enterprise above that; it gives $20 in credits on a first card and matches the first auto-recharge up to $50. On twitterapi.io a returned post is 15 credits ($1 = 100,000 credits), so 1,000 posts are $0.15, about 33x less. Each request has a 15-credit minimum, so a search that returns nothing costs $0.00015; a full page of 20 posts costs $0.003.

Getting started. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); the amount is on the pricing page. Purchased credits never expire, and the monthly plans (Starter $29, Builder $99, Pro $199, Scale $499, Business $1,499) add first-month bonus credits.

If your Puppeteer script also posts. Some Puppeteer projects log in to publish, like or follow. The API has write endpoints for that (/twitter/create_tweet_v2, /twitter/follow_user_v2 and others): one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, and each action then costs 60 credits ($0.0006) per successful call; calls that return status: error are not charged. The call acts as that account, so X can rate-limit, lock or suspend it, keep a normal human pace, and expect the session to need a fresh login now and then.

08 — Section

Moving an existing Puppeteer Twitter scraper to the API

If you inherited a Puppeteer scraper, the migration is mostly deletion. Map each piece to its replacement and remove the browser.

puppeteer.launch(), newPage(), browser.close(). Delete. The API call is a plain fetch; no browser process and no Chrome download in CI or Docker images.

Login steps or browser.setCookie() with a saved session. Delete, and retire the account credentials from your secrets store. Reads need only the X-API-Key header.

page.goto('https://x.com/search?q=...') plus infinite scroll. Replace with /twitter/tweet/advanced_search and the cursor loop. The q you typed into X's search box goes into query unchanged, including operators.

page.goto('https://x.com/<handle>') for a timeline. Replace with /twitter/user/last_tweets (userName=<handle>, 20 posts per page, newest first; the posts are in data.tweets). For profile details, /twitter/user/info returns followers, statusesCount, createdAt and the rest in data; an unknown handle returns HTTP 200 with status: "error" and msg: "user not found".

page.on('response') filters on /i/api/graphql/. Delete, along with the code that walked the nested internal JSON. The API's post object is flat: t.likeCount, t.author.userName, t.extendedEntities.media.

$$eval over article elements and count parsing. Delete. Counts are integers and the text is complete; there is no "Show more" to click.

Retry logic for login checkpoints and error 226. Replace with a fixed back-off on HTTP 429 and 5xx. Those are the only transient states to handle.

After the migration, the script's failure modes are the ones in the API's response: an invalid key, a parameter error in detail, a rate limit, or an empty result when the query matches nothing.

09 — Section

How we collected this

Question: what does it take to collect about 500 posts for one hashtag through a REST API from Node.js, the job people usually attempt with Puppeteer: how many requests, how much wall time, how many posts per page and duplicates, what span the posts cover, and which fields arrive as structured JSON.

Query: #javascript on /twitter/tweet/advanced_search with queryType=Latest, following next_cursor for 26 pages.

Method: a rate-limited, read-only study client that shares a 5-requests-per-second budget with other jobs; wall time measured around the whole run with the system clock. 26 requests, 520 posts, collected in 2026. The analysis counted posts per page, duplicate IDs, the span between the oldest and newest createdAt, field presence (media, links, hashtags, mentions, replies, quotes), engagement count distributions and author aggregates.

What the sample cannot show: one hashtag over a few days is one slice of X; other queries will differ in volume, language and engagement. Wall time reflects our shared client's queueing, not raw API latency. We did not run Puppeteer against x.com, so there is no measured Puppeteer time, post count or block rate on this page; the Puppeteer side is described from its documentation and X's published rules.

Aggregates only. The posts' authors are private individuals, so no handle, post text or ID is published; the raw search pages were analyzed locally and not kept with the study, which holds only the aggregate results and de-identified rows.

javascript
// twitter-hashtag-export.mjs - the REST replacement for a Puppeteer scraper:
// search X (Twitter) for a query, follow next_cursor, write JSONL and CSV.
//
//   node --version                      # 18 or newer (built-in fetch)
//   export TWITTERAPI_IO_API_KEY=...    # from the twitterapi.io dashboard
//   node twitter-hashtag-export.mjs "#javascript" 500
//
// Cost: 15 credits per post returned ($0.15 per 1,000); 500 posts is about $0.075.
import fs from "node:fs";

const API = "https://api.twitterapi.io";
const KEY = process.env.TWITTERAPI_IO_API_KEY;
if (!KEY) throw new Error("set TWITTERAPI_IO_API_KEY");

const query = process.argv[2] ?? "#javascript";      // any advanced-search query: "#javascript lang:en min_faves:5"
const target = Number(process.argv[3] ?? 500);
const PAUSE_MS = 250;                                 // fixed pacing; 5000 before your first payment
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function getPage(cursor) {
  const params = new URLSearchParams({ query, queryType: "Latest" });
  if (cursor) params.set("cursor", cursor);
  for (let attempt = 1; attempt <= 5; attempt++) {
    const res = await fetch(`${API}/twitter/tweet/advanced_search?${params}`, {
      headers: { "X-API-Key": KEY },
    });
    if (res.status === 429 || res.status >= 500) {    // rate limit or a transient error: fixed back-off
      await sleep(5000 * attempt);
      continue;
    }
    if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
    const body = await res.json();
    if (body.status === "error") throw new Error(body.msg);
    return body;                                       // { tweets: [...], has_next_page, next_cursor }
  }
  throw new Error("gave up after 5 attempts");
}

function toRow(t) {
  return {
    id: t.id,
    url: t.url,
    created_at: new Date(t.createdAt).toISOString(), // createdAt: "Thu Oct 16 12:34:56 +0000 2026"
    lang: t.lang,
    text: t.text,
    likes: t.likeCount,
    reposts: t.retweetCount,
    replies: t.replyCount,
    quotes: t.quoteCount,
    views: t.viewCount,
    bookmarks: t.bookmarkCount,
    is_reply: Boolean(t.isReply),
    is_quote: Boolean(t.quoted_tweet),
    author: t.author?.userName ?? "",
    author_followers: t.author?.followers ?? 0,
    hashtags: (t.entities?.hashtags ?? []).map((h) => h.text).join(" "),
    media: (t.extendedEntities?.media ?? []).map((m) => m.type).join(" "),
  };
}

const csvCell = (v) => `"${String(v ?? "").replaceAll('"', '""')}"`;

const seen = new Set();
const rows = [];
let cursor = "";
let requests = 0;
const started = Date.now();

while (rows.length < target) {
  const body = await getPage(cursor);
  requests++;
  for (const t of body.tweets ?? []) {
    if (seen.has(t.id)) continue;                      // de-duplicate across pages
    seen.add(t.id);
    rows.push(toRow(t));
  }
  if (!body.has_next_page || !body.next_cursor) break; // no more results for this query
  cursor = body.next_cursor;
  await sleep(PAUSE_MS);
}

fs.writeFileSync("posts.jsonl", rows.map((r) => JSON.stringify(r)).join("\n") + "\n");
const cols = Object.keys(rows[0] ?? { id: "" });
fs.writeFileSync("posts.csv", [cols.join(","), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(","))].join("\n") + "\n");

const seconds = ((Date.now() - started) / 1000).toFixed(1);
console.error(`${rows.length} posts, ${requests} requests, ${seconds} s, about $${(rows.length * 0.00015).toFixed(3)}`);

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Can Puppeteer still scrape Twitter (X) in 2026?

Puppeteer can open x.com because it drives a real Chrome, but since the June 30, 2023 login wall the useful pages (timelines, search, replies) need a logged-in session, and that session acts as your X account, which X can rate-limit, lock or suspend. X's Terms of Service (effective October 9, 2026) prohibit crawling or scraping without prior written consent, and x.com/robots.txt disallows all paths for generic user agents. For data, an API is the documented route.

Does Puppeteer need an X account to read tweets?

For anything beyond the top of a public profile, yes. The logged-out view of x.com is limited, so Puppeteer tutorials log in or load saved session cookies with browser.setCookie(). Every request then runs as that account. A REST API read needs no X account: twitterapi.io takes an API key in the X-API-Key header.

Can I capture X's GraphQL responses with page.on('response')?

Technically Puppeteer's response event fires for every response a page receives, and HTTPResponse.json() parses the body. But those x.com/i/api/graphql endpoints are internal and undocumented, their query IDs and required headers change without notice, and the browser still has to be logged in. You get JSON instead of HTML, not a stable or permitted interface.

What is the Node.js alternative to a Puppeteer Twitter scraper?

One fetch call per page: GET https://api.twitterapi.io/twitter/tweet/advanced_search with query and queryType=Latest and an X-API-Key header returns up to 20 posts in tweets[], plus has_next_page and next_cursor. Loop until you have enough. Node 18 and newer have fetch built in, so there are no dependencies. In our study it returned 520 posts in 26 requests.

How much does it cost to collect 500 tweets without Puppeteer?

On twitterapi.io each returned post is 15 credits, $0.15 per 1,000, so our 520-post #javascript sample cost $0.078. The official X API pay-per-usage rate is $0.005 per post read, $2.60 for the same 520 posts and about 33x more per 1,000. New accounts get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the amount.

Is Puppeteer or Playwright better for scraping X?

Neither changes the outcome on x.com: both drive a real browser, both meet the same login wall, and the same terms apply to both. Pick between them for testing on their own merits (our Playwright guide covers that library); for X data the choice that matters is browser automation versus an API.

Which Node.js version does Puppeteer need?

The npm registry lists Puppeteer 26.0.0 as the latest release at the time of writing, with node >=22.12.0 in its engines field. npm i puppeteer also downloads Chrome for Testing, about 170 MB on macOS and 282 MB on Linux, into ~/.cache/puppeteer; puppeteer-core skips the download.

Does the API return the same fields a Puppeteer scraper reads from the page?

It returns more, as typed JSON: full text, createdAt, lang, likeCount, retweetCount, replyCount, quoteCount, viewCount and bookmarkCount as integers, entities (hashtags, urls, mentions), extendedEntities.media with the media type, and an author object with userName, followers and isBlueVerified. In our sample 100% of posts had all six counts as integers.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.