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.
// 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)`);
node instagram-profiles.mjs usernames.txtRun it
- 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. - Set HANDLEHAUL_API_KEY. Export the key as the environment variable
HANDLEHAUL_API_KEYso it never sits in the code. - Check Node.js. Run
node --versionand make sure it is 18 or newer, for the built-in fetch. No npm packages are needed. - Save the script as instagram-profiles.mjs. Copy the script above into
instagram-profiles.mjs, and put your input inusernames.txt, one item per line. - 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:
natgeo
@NatGeo
# lines starting with # are skipped
nosuchaccount_0000
export HANDLEHAUL_API_KEY=kd_live_... # your key from the dashboard
node --version # v18 or newer
node instagram-profiles.mjs usernames.txt
$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.
| Job | Calls | Cost |
|---|---|---|
| 100 profiles | 100 | $0.14 to $0.080 |
| 1,000 profiles | 1,000 | $1.40 to $0.80 |
| 10,000 profiles | 10,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.
natgeo: 280000000 followers
nosuchaccount_0000: user_not_found
Saved 1 of 2 profiles to profiles.csv (1 credits)
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.
| Status and code | When | What the script does |
|---|---|---|
404 user_not_found | No account with that username | The script writes a row with the error code and goes on (failed calls are free). |
403 private_account | Returned instead of a profile in rare cases | The script writes a row with the error code and goes on (failed calls are free). |
401 invalid_api_key | The key is missing, wrong or revoked | Stops with the message. Check the variable with echo $HANDLEHAUL_API_KEY. |
402 insufficient_credits | The account is out of credits | Stops. Rows already fetched stay in the file. |
429 rate_limited | Too many requests per second | Waits for Retry-After and retries, up to 5 times. Not charged. |
502 / 503 / 504 | Data temporarily unavailable or slow | Retries 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.
// 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);
Next steps
- Instagram API in Python: bulk profiles to CSV: the same script in Python.
- Instagram profile API: what the endpoint returns and how it compares.
- Instagram profile API docs: every parameter, field and error.
- All tutorials: other jobs on Instagram and TikTok, in Python and Node.js.
Bulk Instagram profiles to CSV with Node.js: questions
How do I run several lookups at once in Node?
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?
Can I get the profile picture too?
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?
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.