Skip to content
← All articles
Publish Instagram Reels and Carousels with Node.js

Publish Instagram Reels and Carousels with Node.js

Publishing Instagram content from Node.js is a two-stage operation. First you ask Meta to create and process a media container. Then you publish that container. A successful response from the first request does not mean the Reel is live.

This guide uses the Instagram Login route and the native fetch API in Node.js. The examples are deliberately small: two public image URLs for a carousel and one video URL for a Reel. They are documentation-based examples, not a live publication test. The actual authorization and media capabilities of your app must be checked before using them in production.

If you prefer a unified scheduling API instead of maintaining the Meta integration, see the PostSider Instagram API guide.

1. Prepare the professional account and application

Use an eligible Instagram professional account and a Meta app configured for Instagram Login. Obtain an authorized access token with the required scopes, including the applicable content-publishing permission, and the Instagram professional account ID.

The Instagram Login and Facebook Login routes are not interchangeable. Instagram Login uses graph.instagram.com and the Instagram business permission family; Facebook Login has its own token, Page and permission requirements. Follow Meta’s platform overview and changelog when setting up access. If publishing for accounts you do not own or manage, confirm the applicable access and app-review requirements.

Set the following environment variables in a server-side process:

export IG_API_VERSION="v27.0"
export IG_USER_ID="your-instagram-professional-account-id"
# Supply IG_ACCESS_TOKEN through your secret manager.

The example version matches the current publishing documentation reviewed for this article. Use a version supported by your app; do not silently upgrade an existing integration without testing.

Store the token outside source control. Do not copy it into a browser bundle or include it in request logs.

2. Create a small HTTP client

The following example uses JSON request bodies and a Bearer authorization header, as shown in Meta’s publishing documentation. Save it as instagram.mjs. The URLs supplied later are placeholders; replace them with media that your account is authorized to publish.

import { setTimeout as sleep } from 'node:timers/promises';

const { IG_API_VERSION, IG_USER_ID, IG_ACCESS_TOKEN } = process.env;
if (!IG_API_VERSION || !IG_USER_ID || !IG_ACCESS_TOKEN) {
  throw new Error('Instagram configuration is incomplete');
}
if (!/^v\d+\.\d+$/.test(IG_API_VERSION) || !/^\d+$/.test(IG_USER_ID)) {
  throw new Error('Invalid Instagram API version or account ID');
}

const base = 'https://graph.instagram.com/' + IG_API_VERSION;

async function graph(path, body) {
  const response = await fetch(base + path, {
    method: body === undefined ? 'GET' : 'POST',
    headers: {
      Authorization: 'Bearer ' + IG_ACCESS_TOKEN,
      'Content-Type': 'application/json',
    },
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(30000),
  });
  const result = await response.json();
  if (!response.ok || result.error) {
    // Record a sanitized status and error code, not the token or request.
    throw new Error('Meta error ' + response.status +
      ' / ' + (result.error?.code ?? 'unknown'));
  }
  return result;
}

export async function createContainer(fields) {
  const result = await graph('/' + IG_USER_ID + '/media', fields);
  if (!result.id) throw new Error('Missing media container ID');
  return result.id;
}

export async function waitUntilReady(id) {
  for (let attempt = 0; attempt < 5; attempt++) {
    const result = await graph('/' + encodeURIComponent(id) +
      '?fields=status_code');
    if (result.status_code === 'FINISHED') return;
    if (['ERROR', 'EXPIRED', 'PUBLISHED'].includes(result.status_code)) {
      throw new Error('Container state: ' + result.status_code);
    }
    if (attempt < 4) await sleep(60000);
  }
  throw new Error('Container not ready; reconcile before retrying');
}

export async function publishContainer(id) {
  const result = await graph('/' + IG_USER_ID + '/media_publish', {
    creation_id: id,
  });
  if (!result.id) throw new Error('Missing published media ID');
  return result.id;
}

The polling loop is bounded and intentionally conservative. In a real queue worker, persist the next check time rather than holding a process open for minutes. This example does not automatically retry writes: a network timeout can occur after Meta has accepted a request.

3. Publish a Reel

Meta must be able to retrieve the media URL without your local browser session. A link pointing at localhost, a private drive or an expired signed object will not work.

Create a Reel container using the REELS type and video URL. Keep the returned container ID before moving to publication.

import {
  createContainer, waitUntilReady, publishContainer
} from './instagram.mjs';

const container = await createContainer({
  media_type: 'REELS',
  video_url: 'https://media.example.com/demo.mp4',
  caption: 'A short demonstration of our new feature.',
});

console.log('Container:', container);
// Persist container and job ID in a durable store here.
await waitUntilReady(container);
const mediaId = await publishContainer(container);
console.log('Published media ID:', mediaId);

A published Reel can appear as VIDEO in the media-type field. Meta recommends inspecting media_product_type to determine its product category. Check your account’s actual video constraints and processing state instead of assuming every MP4 file is accepted.

Create one child container for each image, using is_carousel_item. Then create a parent container whose children are the returned IDs in display order. Publish only the parent.

import {
  createContainer, waitUntilReady, publishContainer
} from './instagram.mjs';

const urls = [
  'https://media.example.com/slide-1.jpg',
  'https://media.example.com/slide-2.jpg',
];
const children = [];
for (const image_url of urls) {
  const child = await createContainer({
    image_url,
    is_carousel_item: true,
  });
  // Persist the child ID and its position for recovery.
  await waitUntilReady(child);
  children.push(child);
}

const parent = await createContainer({
  media_type: 'CAROUSEL',
  children: children.join(','),
  caption: 'Two examples from the same release.',
});
// Persist parent ID before attempting the publish.
await waitUntilReady(parent);
console.log('Published media ID:', await publishContainer(parent));

The code uses two images to avoid conflating the consumer-app carousel limit with limits that vary across API versions and documentation. Verify the current supported maximum, media specifications and permitted mixes of images and video. Meta’s current content-publishing guide also describes cropping based on the first carousel image; prepare assets with a consistent intended aspect ratio.

5. Turn the example into a reliable scheduling worker

A production job needs an identity that outlives the process. Store your internal job ID, destination ID, scheduled time, asset references, child and parent container IDs, state and published media ID.

Create containers close enough to publication that they will still be valid. A long-term schedule is an application-level record, not a container that you create weeks in advance. Check Meta’s current container lifetime and the account’s content publishing limit before delivery.

Distinguish these outcomes:

OutcomeNext action
Container returnedPersist its ID and wait for processing
Container still processingSchedule a later status check
Container failed or expiredRecord the failure and investigate before replacement
Publish returned a media IDSave it and verify the resulting media
Publish request timed outReconcile container and account state; do not immediately publish again

The timeout case matters because your server can lose the response even when the network accepted publication. Retrying blindly can duplicate content. Read the existing container and available media records, and send ambiguous cases to a review queue. See idempotency for social posting for the general pattern.

Validate the asset before creating a container

A media publishing error is often easier to prevent than to recover from. Separate the checks your application can perform locally from the checks that only Instagram can perform during media processing.

For each asset, record the actual file type, dimensions, byte size and, for video, duration and codec information. Do not rely on its filename extension alone. A file named with an MP4 extension can still contain a codec or stream arrangement that the target service rejects. Compare the measured metadata with the specifications for your selected publishing route and API version.

Check the final URL too. The URL must point to the media itself, not an HTML page containing a player or download button. A browser may follow redirects, send cookies and perform authentication that Meta’s media fetching infrastructure cannot reproduce.

One useful preflight is to inspect the URL using a separate HTTP client with no cookies from your browser. This can reveal incorrect content types, redirects or authentication requirements. It cannot prove that Meta can access the asset from its own infrastructure, so a successful check is not a guarantee of publication.

If using signed object-storage URLs, make sure their validity covers the time when the container is created and processed. A video URL generated when a customer schedules a post for next week may be expired long before the worker starts. Generate the required URL close to processing time or keep a stable permitted media location available until delivery completes.

For user-supplied media URLs, do not implement a backend fetcher that blindly requests arbitrary addresses. Restrict fetching to approved storage locations or use a properly isolated, validated fetch service. An attacker could otherwise provide a URL that causes your worker to contact a private infrastructure endpoint. Avoid logging signed media URLs because their query strings can contain credentials.

For a carousel, also verify the intended order before creation. Prepare images around a consistent aspect ratio and review how the final composition will look when cropped. Do not depend on the platform to choose the same framing your designer intended.

Keep the worker’s state separate from Instagram’s state

Your application needs to remember more than the most recent response from Meta. A useful production model has a persistent internal publishing job and separate records for the media containers associated with it.

The job might begin in a scheduled state. When the scheduled time arrives, a worker claims it and moves it to preparing. After creating containers, the worker stores their IDs and moves the job to processing. Once the parent or Reel is ready, the job becomes eligible for publication. A verified successful delivery ends the job in a published state.

These are proposed application states, not names of undocumented Meta API statuses. Keep them distinct from the actual status_code returned for a media container.

Application stateRequired local record
ScheduledAccount, future time, caption, immutable asset references
PreparingWorker claim and attempt identifier
ProcessingPersisted child or Reel container IDs
ReadyReady container ID and the intended publish action
UnknownEvidence of an ambiguous request and next reconciliation step
PublishedResulting media ID and publication time
FailedSanitized error details and recovery decision

A durable job claim matters because workers can overlap. A deployment might start a replacement process while an old process is still handling a job. A timer may fire twice, or a queue may redeliver a message after a visibility timeout.

Use a transactional claim or an equivalent queue mechanism to prevent two workers from deliberately publishing the same internal job simultaneously. Do not confuse that local safeguard with a guarantee of exactly-once delivery at a remote API. A worker can lose its connection after the platform processes the request, and the local transaction cannot roll back a remote publication.

Before calling the publish endpoint, record that a publish attempt is about to occur. If the process crashes, the next worker knows it must reconcile that attempt before making another write. After receiving a successful result, save the media ID immediately.

For a carousel, preserve the relationship between each child ID and its ordinal position. If the worker resumes with some children created, it should determine whether they are still valid rather than blindly recreating the entire set. A changed media asset should be treated as a deliberate revision of the job, not silently mixed with the old children.

Troubleshoot a failed publication in the correct order

Start with the exact request that failed. Container creation, container status inspection and publication are distinct operations. A failure at one stage does not establish that the others are broken.

If a creation request returns an authorization error, confirm the account ID, login route, required permission and token state. Do not request broader permissions merely to see whether the error goes away. The minimum authorization appropriate to the intended action is easier to audit.

If a container remains in processing, record its last reported status and check the documented polling guidance. Avoid treating a long transcode as a failed publish. Repeating creation while the original container is still processing can waste resources and make diagnosis harder.

If the container reports a terminal error, examine the available error details, media URL and metadata. A missing file, unsupported encoding and revoked account access need different recovery actions. Repeating the same payload cannot repair a permanent validation problem.

If publication returns a timeout or transport failure, retain the original container ID and move the job to an uncertain state. Read the status of the known container and the account’s available media records. Where the platform reports publication but your application lacks the returned media ID, avoid guessing which recent media object belongs to the job. A duplicate caption does not uniquely identify a publication.

The official Instagram API collection documents status inspection alongside publication operations. Use the response fields available for your configured API version, rather than assuming a third-party SDK exposes everything the native API returns.

If you cannot establish what happened, retain the job for an operator. Show the account, attempted time and relevant identifiers, with a link to the network’s native account interface where appropriate. Do not expose access tokens, signed URLs or other credentials in the support screen.

Schedule around processing time and account capacity

Suppose a customer wants a Reel to go live at nine in the morning. Creating the media container at exactly nine does not guarantee that the Reel will be public at that time. The platform may need to fetch and process the video first.

Design the worker so that preparation can happen before the intended publication time without publishing early. Use observed processing durations from your own jobs to determine the appropriate preparation window. Do not create the container so far ahead that it expires before use. Verify the current container lifetime in the content publishing documentation.

A processing job that misses its intended time needs an explicit policy. For evergreen content, a modest delay may be acceptable. A time-sensitive announcement may need manual review instead of late automatic publication. Store this choice when the schedule is created rather than improvising during an incident.

Check the account’s applicable publishing capacity as well. A worker that handles many jobs in a shared queue should not assume that a single application’s request allowance and an individual Instagram account’s publishing allowance are the same thing. Review the current content publishing limit reference for the configured route and account. Published limits have differed across Meta references and versions, so a hard-coded number copied from a tutorial is not a durable capacity check.

When scheduling across multiple customers, isolate their workloads. A single account with a large carousel backlog should not monopolize all workers or cause every other customer to miss their schedule. Use per-account concurrency limits and bounded retries appropriate to the documented response.

Test the failure paths without posting to a customer’s feed

Start by mocking the HTTP client. For a Reel, return a valid container ID, then a processing response, then a ready response, and finally a published media ID. Confirm that the worker calls publication only after readiness.

Next, make container creation fail permanently. The worker should not proceed to status inspection with a missing ID. Simulate a processing timeout and confirm that the original ID is retained. Finally, simulate a lost publish response: the recovery path must not issue another publication request before reconciling the old attempt.

For a carousel, return distinct IDs for three assets and assert that the parent request preserves their order. Simulate the second child failing and confirm the parent is not created prematurely.

Unit tests exercise your own control flow, not Instagram’s real capabilities. After the mocked tests pass, use an authorized test professional account and assets you own. Establish the exact app version, token route and account type. Publish one controlled image carousel and one controlled Reel, verify their appearance, and check the resulting IDs in your own records.

Document the date of the successful test and the settings used. Repeat the smoke test when upgrading the Graph API version or changing a media pipeline. This is how a short working Node.js script becomes an integration that another developer can maintain.

When a unified API is more practical

If Instagram is your only platform, maintaining its native integration may be reasonable. If you also publish to TikTok, LinkedIn and X, you will need to repeat much of the authentication, media validation and delivery logic for other networks.

PostSider exposes a shared social publishing API with connected channel IDs, media references and future publication dates. Your Node service can use the Node.js integration guide and the media reference for the current supported payloads. Provider-specific options still need validation; a unified interface cannot remove Instagram’s native restrictions.

Sources

Documentation reviewed December 1, 2026. Examples require your own credentials and media; no live account was used to publish content for this guide.

Frequently asked questions

Can Node.js publish Instagram Reels through the API?

Yes, for eligible professional accounts with the required authorization. Create a Reel media container, wait for successful processing, then publish the container using the Instagram API.

Can I publish an Instagram carousel through Node.js?

Yes. Create individual child containers, create a carousel parent with their IDs in order, and publish the parent container once it is ready.

Can I schedule Instagram posts directly through the Graph API?

This publishing flow creates and publishes media containers. To publish at a future time, run your own durable scheduler or use a publishing service with a scheduling API.

Does Instagram Login require a Facebook Page?

The Instagram Login route does not require a linked Facebook Page. The Facebook Login route has different host, token and permission requirements.

Let your AI post
to social media for you.

Connect your accounts, add PostSider to your AI and publish your first post in a few minutes.

7-day free trial · 30+ networks · No credit card · Cancel anytime