Tutorial · Instagram · Node.js

Bulk Instagram profiles to CSV with Node.js

To fetch many Instagram profiles with Node.js, call /v1/instagram/users/by-username/{username} for each username with the built-in fetch and append one CSV row per account. The script below reads usernames.txt, drops duplicates and blank lines, and writes the CSV by hand with proper quoting.

Short answer. Run node instagram-profiles.mjs usernames.txt with HANDLEHAUL_API_KEY set. profiles.csv gets the id, counts, verified and business flags, category, link and bio of each public account. 1,000 profiles cost $1.40 to $0.80; usernames with no account are free.

Facts checked 2 December 2026. Prices change: follow the links before you decide.

What you need

  • An API key. Sign up and create one in the dashboard. A sandbox key (kd_test_) returns sample data for free, so you can run the script before you spend anything.
  • Node.js 18 or newer, for the built-in fetch. No npm packages: the CSV is written by hand with proper quoting.
  • The key in HANDLEHAUL_API_KEY. The script reads it from the environment, so the key never sits in your code or your repository.
  • Public Instagram accounts. The API returns public data only: no logins, no private accounts, no DMs.

The script

It calls GET /v1/instagram/users/by-username/{username} (see the Instagram profile API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as instagram-profiles.mjs.

instagram-profiles.mjs
// Fetch public Instagram profiles for a list of usernames and save them to CSV.
// Usage: node instagram-profiles.mjs usernames.txt   (one username per line)
// Needs Node 18+ (built-in fetch) and HANDLEHAUL_API_KEY in the environment. No dependencies.
import { readFileSync, writeFileSync, appendFileSync } from "node:fs";

const API = "https://api.handlehaul.com";
const KEY = process.env.HANDLEHAUL_API_KEY;
if (!KEY) fail("Set HANDLEHAUL_API_KEY first, e.g. export HANDLEHAUL_API_KEY=kd_live_...");

function fail(message) {
  console.error(message);
  process.exit(1);
}

class ApiError extends Error {
  constructor(status, code, message) {
    super(`HTTP ${status} ${code}: ${message}`);
    this.status = status;
    this.code = code;
  }
}

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

// One API call. Waits and retries on 429 (honouring Retry-After) and on 502/503/504,
// throws ApiError for any other error. Failed calls and 429 answers are not charged.
async function get(path, params = {}) {
  const url = new URL(API + path);
  for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(url, { headers: { "X-Api-Key": KEY } });
    if ([429, 502, 503, 504].includes(res.status) && attempt < 5) {
      const wait = Number(res.headers.get("retry-after")) || 2 ** attempt;
      console.error(`  HTTP ${res.status}, retrying in ${wait}s`);
      await res.arrayBuffer();
      await sleep(wait);
      continue;
    }
    const body = await res.json().catch(() => ({}));
    if (res.ok) return body;
    const err = body.error ?? {};
    throw new ApiError(res.status, err.code ?? "unknown", err.message ?? res.statusText);
  }
}

// CSV by hand (RFC 4180): quote a cell when it holds a comma, a quote or a line break.
const cell = (v) => {
  const s = v == null ? "" : String(v);
  return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
const csvLine = (values) => values.map(cell).join(",") + "\r\n";

const FIELDS = ["input", "id", "username", "full_name", "followers", "following", "posts", "is_private",
  "is_verified", "is_business", "category", "external_url", "biography", "error"];
const SKIP = new Set(["user_not_found", "private_account"]); // note these and go on (failed calls are free)

const file = process.argv[2];
if (!file) fail("Usage: node instagram-profiles.mjs usernames.txt");
const lines = readFileSync(file, "utf8").split(/\r?\n/).map((l) => l.trim());
// drop blanks, comments and duplicates: each call costs a credit
const names = [...new Set(lines.filter((l) => l && !l.startsWith("#")).map((l) => l.replace(/^@/, "").toLowerCase()))];
const out = "profiles.csv";

writeFileSync(out, "" + csvLine(FIELDS)); // the BOM lets Excel read emoji and accents
let done = 0, credits = 0;
for (const name of names) {
  let body;
  try {
    body = await get(`/v1/instagram/users/by-username/${encodeURIComponent(name)}`);
  } catch (e) {
    if (!SKIP.has(e.code)) fail(`Stopped: ${e.message}\n${done} profiles saved in ${out}`);
    appendFileSync(out, csvLine(FIELDS.map((f) => ({ input: name, error: e.code })[f])));
    console.log(`${name}: ${e.code}`);
    continue;
  }
  const p = body.data;
  credits += body.meta.credits_charged ?? 0;
  const row = { ...p, ...p.counts, input: name, error: "" };
  appendFileSync(out, csvLine(FIELDS.map((f) => row[f])));
  done++;
  console.log(`${name}: ${p.counts.followers} followers`);
}
console.log(`Saved ${done} of ${names.length} profiles to ${out} (${credits} credits)`);
Tested 2026-12-02 against the documented API responses on Node.js 26, using only Node 18 features. Run: node instagram-profiles.mjs usernames.txt

Run it

  1. Get an API key. Sign up at api.handlehaul.com/signup and create a key. A sandbox key (kd_test_) returns sample data for free while you test.
  2. Set HANDLEHAUL_API_KEY. Export the key as the environment variable HANDLEHAUL_API_KEY so it never sits in the code.
  3. Check Node.js. Run node --version and make sure it is 18 or newer, for the built-in fetch. No npm packages are needed.
  4. Save the script as instagram-profiles.mjs. Copy the script above into instagram-profiles.mjs, and put your input in usernames.txt, one item per line.
  5. Run it. Run node instagram-profiles.mjs usernames.txt. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.

Example usernames.txt:

usernames.txt
natgeo
@NatGeo
# lines starting with # are skipped
nosuchaccount_0000
Terminal
export HANDLEHAUL_API_KEY=kd_live_...   # your key from the dashboard
node --version                  # v18 or newer
node instagram-profiles.mjs usernames.txt
On Windows PowerShell, set the key with $env:HANDLEHAUL_API_KEY="kd_live_...".

How it works

One call per username. The script calls /v1/instagram/users/by-username/{username} for each line. This route always reads its input as a username, so all-digit usernames work as they are.

Duplicates. Usernames are lower-cased and de-duplicated before any call, because each successful call is charged. A leading @ is dropped.

Missing and private accounts. A username with no account answers 404 user_not_found: the script writes the code in the error column and goes on, and the call is free. A private account still returns its public profile fields with is_private set to true; its follower list and posts are not available.

Keep the id. Every row carries the numeric id. Ids survive username changes: store them and use /v1/instagram/users/by-id/{id} next time, or pass the id to the followers and posts endpoints to skip the lookup credit.

Freshness. Profiles are cached for 60 seconds and a cached answer is free; meta.cache_age_seconds says how old it is. Add fresh=true to force a live fetch.

What it costs

Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per profile that exists. Usernames with no account, and answers from the 60-second cache, are free.

Calls and cost for bulk instagram profiles to csv
JobCallsCost
100 profiles100$0.14 to $0.080
1,000 profiles1,000$1.40 to $0.80
10,000 profiles10,000$14.00 to $8.00

The script makes one call at a time, well under the account limit of 10 to 30 requests per second. Each response says what it cost in meta.credits_charged, and the script adds those up in its last line.

Sample output

An example run with example values, not a real export. Field names and shapes are the ones in the API docs.

Terminal
natgeo: 280000000 followers
nosuchaccount_0000: user_not_found
Saved 1 of 2 profiles to profiles.csv (1 credits)
profiles.csv
input,id,username,full_name,followers,following,posts,is_private,is_verified,is_business,category,external_url,biography,error
natgeo,787132,natgeo,National Geographic,280000000,160,30500,false,true,true,Media/news company,https://www.nationalgeographic.com,Experience the world through the eyes of our photographers.,
nosuchaccount_0000,,,,,,,,,,,,,user_not_found

Common errors

Errors come back as { "error": { "code", "message", "request_id" } } with an HTTP status. Failed calls are never charged. Full list: error codes.

Errors this script can meet and what it does
Status and codeWhenWhat the script does
404 user_not_foundNo account with that usernameThe script writes a row with the error code and goes on (failed calls are free).
403 private_accountReturned instead of a profile in rare casesThe script writes a row with the error code and goes on (failed calls are free).
401 invalid_api_keyThe key is missing, wrong or revokedStops with the message. Check the variable with echo $HANDLEHAUL_API_KEY.
402 insufficient_creditsThe account is out of creditsStops. Rows already fetched stay in the file.
429 rate_limitedToo many requests per secondWaits for Retry-After and retries, up to 5 times. Not charged.
502 / 503 / 504Data temporarily unavailable or slowRetries with a growing wait (1, 2, 4, 8, 16 s). Failed calls are free.

The same job with the SDK

If you would rather not maintain the HTTP code, the official JavaScript SDK (npm install handlehaul) does the paging, retries 429 for you and raises typed errors. The script above is the same job with every request visible.

Node SDK
// npm install handlehaul
import { HandleHaul } from "handlehaul";

const hh = new HandleHaul(); // reads HANDLEHAUL_API_KEY
const { data: p } = await hh.instagram.profileByUsername("natgeo");
console.log(p.id, p.counts.followers, p.category);
Source and reference: handlehaul-js on GitHub.

Next steps

Bulk Instagram profiles to CSV with Node.js: questions

How do I run several lookups at once in Node?
Split the list into small batches and await Promise.all() each batch, keeping the total under your account’s requests-per-second limit (rate limits). The get() helper already waits and retries on 429.
Why is the bio in quotes in the CSV?
Bios often contain commas and line breaks. The script wraps any cell with a comma, quote or line break in double quotes and doubles inner quotes (RFC 4180), so Excel, Google Sheets and CSV libraries read it as one cell.
Can I get the profile picture too?
Each profile has profile_pic_url and profile_pic_url_hd. Add them to FIELDS to put them in the CSV. They are Instagram CDN links that expire after a while, so download what you need soon.
Which username formats does it accept?
Plain usernames, with or without a leading @, in any case. The route always reads the input as a username, so all-digit usernames work too.

Run it on your own list

One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls are free.

Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.