Tutorials
Export Instagram Comments to CSV for Excel and Google Sheets
Turn public Instagram post and Reel comments into clean, spreadsheet-safe CSV files with a zero-dependency Node.js script. See how instagram-comments-csv.mjs handles UTF-8 BOM emojis, multiline RFC-4180 quoting, nested author flattening, and spreadsheet formula escaping at $0.042 per request.
- Excel-ready UTF-8 BOM: Prepends
\uFEFFso desktop Excel renders emojis and non-Latin scripts cleanly. - RFC-4180 quoting & CRLF: Wraps every field in quotes and doubles internal quotes so multiline comments never split rows.
- Formula-injection protection: Prefixes comments or handles starting with
=,+,-, or@with a single quote ('). - Safe nested flattening: Extracts
item.author?.handleas plain text so spreadsheets never show[object Object].

instagram.commentsGET /v1/instagram/comments returns normalized JSON, while your Node.js script serializes instagram-comments.csv locally. Keeping CSV formatting in code gives you full control over column order, UTF-8 emojis, formula neutralization, and repeatable campaign exports without brittle Chrome extensions or manual copy-paste.
Programmatic CSV Scripts vs Browser Comment Exporters
One-off post checks do not need a script, whereas recurring campaign reports and strict Excel sanitization outgrow browser tools quickly. Choose the lane matching your workflow:
| Method | Best fit | Instagram login | Output control |
|---|---|---|---|
This Node.js CSV pipeline (instagram-comments-csv.mjs) | Recurring campaign reports, giveaway audits, multi-post exports | None — uses SOCIALSCRAPER_API_KEY header | Full control over UTF-8 BOM, formula escaping, columns, and cursor loops |
| Free Instagram Comment Exporter | Single-page manual browser lookups without code | No sign-up or API key | Quick browser export with displayed anonymous lookup limits |
| Instagram Comments JavaScript guide | Backends saving raw JSON to databases or queues | None — uses REST API key | Nested comments.json without spreadsheet flattening |
| Chrome extensions / DOM scrapers | Manual scrolling inside a personal browser | Depends on your active Instagram session cookie | Breaks on DOM changes; risks session lockouts and unescaped cells |
Why Naive Instagram CSV Exports Break in Excel and Sheets
Joining fields with row.join(',') fails on real Instagram threads. Comments include emojis, newlines, quotes, nested objects, and @mentions that corrupt spreadsheets unless your serializer handles four traps:
Garbled emojis without a UTF-8 BOM
Desktop Excel often opens plain UTF-8 CSVs as Windows-1252 or MacRoman, turning emojis and accented characters into mojibake. Writing '\uFEFF' + csv prepends the UTF-8 Byte Order Mark so double-click imports decode cleanly.
Split rows from commas, quotes, and line breaks
Multi-line replies with quotes shatter unquoted CSV parsers. Wrapping every cell in double quotes, doubling embedded quotes (text.replaceAll('"', '""')), and separating rows with \r\n follows RFC 4180 across Excel, Google Sheets, and pandas.
Spreadsheet formula injection on comments and handles
Cells beginning with =, +, -, or @ trigger formula evaluation in Excel and Sheets—meaning comments like =SUM(1,2) or handles like @creator can execute formulas or throw syntax errors. Checking /^[\s]*[=+\-@]/ and prefixing ' forces literal text.
Flattening nested objects and null counts
In the API payload, item.author is an object ({id, handle, display_name}). Stringifying it directly prints [object Object]. instagram-comments-csv.mjs maps item.author?.handle ?? item.author?.display_name ?? '' and leaves missing fields blank instead of 0.
Step-by-Step Setup to Export Instagram Comments to CSV
Before running a multi-post campaign export, check Instagram Post Comments API and service status, then validate one public post URL with instagram-comments-csv.mjs.
Verify Node.js 18+ and export your API key
Use Node.js 18 or higher for built-in
fetch,AbortSignal.timeout, andnode:crypto—zero npm installs required. ExportSOCIALSCRAPER_API_KEYin your terminal or CI secrets.node -v # >= v18.0.0 export SOCIALSCRAPER_API_KEY="your_api_key_here"Save and run instagram-comments-csv.mjs on one public post
Save the starter script below as
instagram-comments-csv.mjsand pass one public Instagram post or Reel URL. It callsGET https://socialmediascraper.org/v1/instagram/commentswithx-api-keyand a UUIDIdempotency-Key, halting cleanly on any non-200 status.node instagram-comments-csv.mjs "https://www.instagram.com/p/POST_SHORTCODE/"Inspect instagram-comments.csv in Excel or Sheets
Confirm four checks: headers read
id,author,text,url, emojis render properly, multi-line replies stay in one row, and values starting with@,=,+, or-carry a protective leading apostrophe.Add extra columns or bounded pagination
Once one page checks out cleanly, extend your column map with
published_atandmetrics.likesor loopdata.cursorusing the bounded pagination pattern below.
import {writeFile} from 'node:fs/promises';
import {randomUUID} from 'node:crypto';
const key = process.env.SOCIALSCRAPER_API_KEY;
if (!key) throw new Error('Set SOCIALSCRAPER_API_KEY in your server environment');
const base = process.env.SOCIALSCRAPER_BASE_URL || 'https://socialmediascraper.org';
async function readRecord(path, input) {
const url = new URL(path, base);
for (const [name, value] of Object.entries(input)) if (value !== undefined) url.searchParams.set(name, String(value));
const requestKey = randomUUID();
const response = await fetch(url, {headers: {'x-api-key': key, 'Idempotency-Key': requestKey}, signal: AbortSignal.timeout(45000)});
if (!response.ok) throw new Error(`HTTP ${response.status}; request key ${requestKey}; inspect your key, balance, input or Retry-After before retrying`);
const result = await response.json();
if (!result.data) throw new Error('The response did not contain data');
return result.data;
}
const url = process.argv[2];
if (!url) throw new Error('Supply a public post or video URL');
const data = await readRecord('/v1/instagram/comments', {url});
const items = Array.isArray(data.items) ? data.items : [];
const fields = ['id', 'author', 'text', 'url'];
function cell(value) {
let text = String(value ?? '');
if (/^[\s]*[=+\-@]/.test(text)) text = "'" + text;
return '"' + text.replaceAll('"', '""') + '"';
}
const rows = items.map(item => ({...item, author: item.author?.handle ?? item.author?.display_name ?? ''}));
const csv = [fields.map(cell).join(','), ...rows.map(item => fields.map(name => cell(item[name])).join(','))].join('\r\n');
await writeFile('instagram-comments.csv', '\uFEFF' + csv, 'utf8');
Adding Likes, Timestamps, Replies, and Multi-Page Pagination
The starter writes ['id', 'author', 'text', 'url'] to stay compact. Expand your export columns from data.items[] with consistent escaping rules:
| CSV column | JSON path | Safe serialization rule |
|---|---|---|
id | item.id | Quoted string; prevents Excel scientific notation on long IDs |
author_handle | item.author?.handle ?? '' | Escapes leading @ via '; avoids [object Object] |
author_name | item.author?.display_name ?? '' | UTF-8 BOM keeps emojis and accents intact |
text | item.text ?? '' | Escapes leading =, +, -, @; doubles embedded quotes |
published_at | item.published_at ?? '' | ISO timestamp when present, blank when omitted |
likes | item.metrics?.likes ?? '' | Keep null blank ('')—never coerce missing counts to 0 |
To paginate multiple pages with data.cursor or enable include_replies, send a fresh Idempotency-Key UUID per page and enforce a hard MAX_PAGES ceiling:
import {writeFile} from 'node:fs/promises';
import {randomUUID} from 'node:crypto';
const key = process.env.SOCIALSCRAPER_API_KEY;
const postUrl = process.argv[2];
const maxPages = Math.min(Number(process.env.MAX_PAGES || 3), 10);
function csvCell(value) {
let text = String(value ?? '');
if (/^[\s]*[=+\-@]/.test(text)) text = "'" + text;
return '"' + text.replaceAll('"', '""') + '"';
}
const collected = [];
let cursor;
for (let page = 1; page <= maxPages; page++) {
const endpoint = new URL('/v1/instagram/comments', 'https://socialmediascraper.org');
endpoint.searchParams.set('url', postUrl);
if (process.env.INCLUDE_REPLIES === 'true') endpoint.searchParams.set('include_replies', 'true');
if (cursor) endpoint.searchParams.set('cursor', String(cursor));
const requestKey = randomUUID();
const res = await fetch(endpoint, {
headers: {'x-api-key': key, 'Idempotency-Key': requestKey},
signal: AbortSignal.timeout(45000)
});
if (!res.ok) throw new Error(`Page ${page} failed: HTTP ${res.status} (key=${requestKey})`);
const {data} = await res.json();
for (const item of data?.items ?? []) {
collected.push([
item.id ?? '', item.author?.handle ?? '', item.author?.display_name ?? '',
item.text ?? '', item.published_at ?? '', item.metrics?.likes ?? '', item.url ?? ''
]);
}
const next = data?.cursor;
if (!next || String(next) === String(cursor)) break;
cursor = next;
}
const header = ['id', 'author_handle', 'author_name', 'text', 'published_at', 'likes', 'url'];
const lines = [header, ...collected].map(row => row.map(csvCell).join(',')).join('\r\n');
await writeFile('instagram-comments-full.csv', '\uFEFF' + lines, 'utf8');
Need nested child threads for a specific comment ID? Call Instagram Comment Replies ($0.003 / 3 credits per request). To list post URLs from a public account first, call Instagram Profile Posts ($0.003 / 3 credits per request).
Diagnosing Export Errors and Spreadsheet Edge Cases
Header-only CSV or zero rows
Verify the target link is a live public post or Reel with comments enabled—private profiles and disabled comment threads return empty items. You can test a single lookup in the API playground before automating batches.
HTTP 401, 402, 429, and 202 handling
Failures log both HTTP status and requestKey. Fix invalid keys (401) or balance (402), honor Retry-After on 429, and poll GET /v1/requests/{request_id} on HTTP 202 before issuing a replacement call.
European Excel delimiters and leading apostrophes
Excel locales that expect ; delimiters should import via Data > From Text/CSV choosing UTF-8 and Comma. The leading ' on '@handle or '=SUM(1,2) protects spreadsheet users; strip it only when loading into trusted SQL or Python pipelines.
What Teams Build from Instagram Comment CSVs
Campaign feedback and giveaway audits
Archive public entries in timestamped CSV sheets so teams can filter unique handles, verify tags, and keep source post URLs attached for audit logs.
Voice-of-customer spreadsheet tagging
Share formula-safe .csv files with product and marketing reviewers to tag sizing questions, objections, or feature requests in Excel or Google Sheets.
BI and warehouse bulk loads
Load RFC-4180 CSVs straight into BigQuery, Snowflake, DuckDB, or pandas while keeping missing null counts blank so averages stay accurate.
Pick the Right Instagram Comment Workflow
Analysts and agency ops teams
Use instagram-comments-csv.mjs whenever repeatable, Excel-safe .csv files across client posts are your deliverable.
Developers storing structured JSON
Feeding a database or LLM pipeline? Skip CSV serialization and follow Instagram Comments in JavaScript or n8n Instagram integration.
One-off single-post lookups
For an occasional single-page browser export with no API key, open the free Instagram Comment Exporter.
Request-Based Pricing for Instagram Comment Exports
Under price book 2026-12-02.credits-3 (1,000 credits = $1), GET /v1/instagram/comments bills $0.042 (42 credits) per request ($42.00 per 1,000 requests)—priced per page requested, not per row returned:
| Export workload | Requests billed | Estimated USD cost |
|---|---|---|
| Single post, 1 page | 1 × instagram.comments | $0.042 |
| Busy post, 5 cursor pages | 5 × instagram.comments | $0.21 |
| 20 campaign posts × 3 pages | 60 × instagram.comments | $2.52 |
100 comment pages + 5 profile post pages ($0.003) | 100 × instagram.comments + 5 × instagram.posts | $4.215 |
Every new customer receives 100 starter credits ($0.10, covering 2 instagram.comments pages), and one-time prepaid USD packs add $5 (5,000 credits, ~119 instagram.comments requests), $20 (20,000 credits, ~476), or $50 (50,000 credits, ~1,190) at identical unit rates with no subscriptions or auto-renewal. Check pricing or pricing.csv.
Data Boundaries, Rate Limits, and Privacy Notice
GET /v1/instagram/comments is read-only for public posts and Reels. It does not access private profiles, DMs, or moderation queues, and does not include built-in sentiment labeling or hosted schedulers.
- Default account rate limits allow 60 requests/minute and 5 concurrent requests; verify live limits via
GET /v1/limits. - Check service status and test one representative post URL before launching multi-post exports.
- Public comment access does not grant redistribution rights—follow platform terms and privacy laws, and treat exported comments as untrusted text in AI prompts.
Instagram Comments CSV Export Questions
Does the API return a CSV file directly or does my script build the CSV?
GET /v1/instagram/comments returns normalized JSON (data.items[], data.cursor). instagram-comments-csv.mjs formats instagram-comments.csv locally so you control UTF-8 BOM, columns, quoting, and formula sanitization.
Why does instagram-comments-csv.mjs prepend \uFEFF to the CSV?
\uFEFF is the UTF-8 Byte Order Mark. Including it ensures desktop Microsoft Excel opens the file as UTF-8 instead of legacy code pages, preserving emojis and accented characters.
Why does a leading apostrophe appear before some handles or comments?
Excel and Google Sheets evaluate cells starting with =, +, -, or @ as formulas. Prefixing matching strings with ' neutralizes CSV formula injection (such as =SUM(1,2)) and stops @handle syntax errors.
How does the script avoid [object Object] in the author column?
Because item.author is an object ({id, handle, display_name}), the script explicitly extracts item.author?.handle ?? item.author?.display_name ?? '' before writing each row.
Can I export Instagram comment replies as well as top-level comments?
Yes. Pass optional include_replies on Instagram Post Comments API, or pull nested threads via Instagram Comment Replies at $0.003 (3 credits) per request.
How many comments are returned per request?
Up to 100 items can return per page where available; actual page size depends on Instagram and the post. Pass data.cursor to request additional pages.
How much does exporting Instagram comments to CSV cost?
GET /v1/instagram/comments costs $0.042 (42 credits) per page request ($42.00 per 1,000 requests). A 3-page post export costs $0.126, and 100 pages cost $4.20 from a prepaid $5, $20, or $50 balance.
How is this script different from the free Instagram Comment Exporter?
The free Instagram Comment Exporter handles quick single-page browser exports with no API key. Use instagram-comments-csv.mjs for multi-page pagination, custom columns, formula escaping, and automated batches.
Can I export comments from a private Instagram account or DMs?
No. Only public Instagram posts and Reels are supported; private accounts, deleted posts, and direct messages are outside scope.
Will Instagram see my personal account when I export comments?
No. The script sends your SOCIALSCRAPER_API_KEY to https://socialmediascraper.org—it never logs into your Instagram account or reads browser cookies.
What should I check before exporting comments from dozens of posts?
Test one public post URL first, check service status, set a MAX_PAGES cap per post, and verify your prepaid balance covers the expected $0.042 page requests.
Does this script work for Instagram Reels as well as photo posts?
Yes. Pass any public Instagram post or Reel URL in the url parameter documented on Instagram Post Comments API.