Social Media Scraper

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 \uFEFF so 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?.handle as plain text so spreadsheets never show [object Object].
Editorial illustration of a vertical public Instagram post, comment bubbles, and a CSV sheet with anonymous rows
instagram.comments

GET /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:

MethodBest fitInstagram loginOutput control
This Node.js CSV pipeline (instagram-comments-csv.mjs)Recurring campaign reports, giveaway audits, multi-post exportsNone — uses SOCIALSCRAPER_API_KEY headerFull control over UTF-8 BOM, formula escaping, columns, and cursor loops
Free Instagram Comment ExporterSingle-page manual browser lookups without codeNo sign-up or API keyQuick browser export with displayed anonymous lookup limits
Instagram Comments JavaScript guideBackends saving raw JSON to databases or queuesNone — uses REST API keyNested comments.json without spreadsheet flattening
Chrome extensions / DOM scrapersManual scrolling inside a personal browserDepends on your active Instagram session cookieBreaks 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.

  1. Verify Node.js 18+ and export your API key

    Use Node.js 18 or higher for built-in fetch, AbortSignal.timeout, and node:crypto—zero npm installs required. Export SOCIALSCRAPER_API_KEY in your terminal or CI secrets.

    export-key.sh
    node -v   # >= v18.0.0
    export SOCIALSCRAPER_API_KEY="your_api_key_here"
  2. Save and run instagram-comments-csv.mjs on one public post

    Save the starter script below as instagram-comments-csv.mjs and pass one public Instagram post or Reel URL. It calls GET https://socialmediascraper.org/v1/instagram/comments with x-api-key and a UUID Idempotency-Key, halting cleanly on any non-200 status.

    run-csv-export.sh
    node instagram-comments-csv.mjs "https://www.instagram.com/p/POST_SHORTCODE/"
  3. 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.

  4. Add extra columns or bounded pagination

    Once one page checks out cleanly, extend your column map with published_at and metrics.likes or loop data.cursor using the bounded pagination pattern below.

instagram-comments-csv.mjs
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 columnJSON pathSafe serialization rule
iditem.idQuoted string; prevents Excel scientific notation on long IDs
author_handleitem.author?.handle ?? ''Escapes leading @ via '; avoids [object Object]
author_nameitem.author?.display_name ?? ''UTF-8 BOM keeps emojis and accents intact
textitem.text ?? ''Escapes leading =, +, -, @; doubles embedded quotes
published_atitem.published_at ?? ''ISO timestamp when present, blank when omitted
likesitem.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:

paginated-instagram-csv.mjs
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.

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 workloadRequests billedEstimated USD cost
Single post, 1 page1 × instagram.comments$0.042
Busy post, 5 cursor pages5 × instagram.comments$0.21
20 campaign posts × 3 pages60 × 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.