Log inStart Free Trial
easyCoexistence Official APIs

Post to Instagram, TikTok and Facebook from Node.js with one API

With easyCoexistence, a Node.js or TypeScript backend posts to Instagram, Facebook, TikTok, YouTube and LinkedIn through each network's official API. Accounts sign in once through a hosted link; one fetch then returns a fresh token for each job on TikTok, YouTube and LinkedIn, and signed events bring comments and DMs to your route. Agents built on the TypeScript MCP SDK get the same accounts as tools.

15 a day

Video posts TikTok's publishing endpoint accepts per account, at no more than six a minute.

10 min to 30 days

How far ahead a Facebook Page post can be scheduled with published false and a scheduled_publish_time.

x-restli-id

The response header that carries a new LinkedIn post's URN, sent with a 201 status.

5 minutes

How soon TikTok fires a comment.update event after a comment is created, deleted or has its visibility changed.

1 hour

How long a Partner API connect link stays open before its session expires.

How does a Node.js backend connect accounts and get their tokens?

Your backend opens a connect session and the account owner finishes in the browser. A POST to /connect-sessions, with your ec_live_ key as the bearer token, a channel such as tiktok or linkedin, a redirect_url and an external_ref for your customer, returns a url on easycoexistence.com. There the owner signs in on the network's own consent screen and returns to your redirect_url with status=connected and a channel_id; a cancelled attempt can be retried from the same link until it expires, an hour after it was created.

Each job then starts with GET /channels/{id}?credentials=1. The answer holds a token that is valid now (not on Instagram and Facebook, whose tokens are never handed out) plus the fields each network needs: graph_api_base and account_id_on_meta on Instagram and Facebook, api_base and business_id on TikTok, channel_id on YouTube, author_urn and required_headers on LinkedIn. Signed channel.connected, channel.disconnected, channel.removed and channel.suspended events, sent to the events URL set in your dashboard, tell your app when an account changes.

A connect link and per-job credentials with fetch
const EC = "https://easycoexistence.com/api/v1";
const KEY = { Authorization: `Bearer ${process.env.EC_API_KEY}` }; // ec_live_...

type Network = "instagram" | "facebook" | "tiktok" | "youtube" | "linkedin";

// A hosted sign-in link for one of your customers on one network
export async function connectLink(customerId: string, channel: Network): Promise<string> {
  const r = await fetch(`${EC}/connect-sessions`, {
    method: "POST",
    headers: { ...KEY, "Content-Type": "application/json" },
    body: JSON.stringify({
      channel,
      redirect_url: "https://app.example.com/connected",
      external_ref: customerId,
    }),
  });
  const session = (await r.json()) as { url: string; error?: { message: string } };
  if (!r.ok) throw new Error(session.error?.message);
  return session.url; // they come back with ?session=...&status=connected&channel_id=...
}

// At the start of every job: the API base and a token that is valid now
export async function credentials(channelId: string) {
  const r = await fetch(`${EC}/channels/${channelId}?credentials=1`, { headers: KEY });
  const body: any = await r.json(); // the credential fields differ by network
  if (!r.ok) throw new Error(body.error.message);
  if (!body.credentials.access_token) throw new Error(body.credentials.note);
  return body.credentials;
}

How do you post to Instagram and Facebook from Node.js?

Instagram publishes through a container. For a Reel, create it with media_type REELS, the video_url and the caption, poll its status_code until it reads FINISHED, then call media_publish with the container id as creation_id. Meta recommends polling about once a minute and giving up after five minutes; ERROR or EXPIRED means the container will not publish, and one left unpublished for 24 hours expires on its own.

A Facebook Page takes a photo in one call to /{page-id}/photos, with the image url and a caption, while text and links go to /{page-id}/feed. Both accept published false with a scheduled_publish_time, and Meta itself publishes the post when the time comes, between 10 minutes and 30 days ahead. The token travels as a bearer header, the Graph API version is already inside graph_api_base, and the media has to sit at a public URL that Meta downloads.

Publish a Reel and schedule a Page photo
type Meta = { graph_api_base: string; access_token: string };

async function graph(c: Meta, path: string, body?: object) {
  const r = await fetch(`${c.graph_api_base}/${path}`, {
    method: body ? "POST" : "GET",
    headers: { Authorization: `Bearer ${c.access_token}`, "Content-Type": "application/json" },
    body: body && JSON.stringify(body),
  });
  const data: any = await r.json();
  if (!r.ok) throw new Error(data.error?.message ?? `Graph API ${r.status}`);
  return data;
}

export async function postReel(channelId: string, videoUrl: string, caption: string) {
  const c = await credentials(channelId);
  const ig = c.account_id_on_meta;
  const { id } = await graph(c, `${ig}/media`, { media_type: "REELS", video_url: videoUrl, caption });
  for (let check = 0; check < 5; check++) {
    await new Promise((wake) => setTimeout(wake, 60_000)); // about once a minute, as Meta advises
    const { status_code } = await graph(c, `${id}?fields=status_code`);
    if (status_code === "FINISHED") return graph(c, `${ig}/media_publish`, { creation_id: id });
    if (status_code === "ERROR" || status_code === "EXPIRED") throw new Error(`Reel container ${status_code}`);
  }
  throw new Error("The Reel is still processing after five minutes");
}

export async function schedulePagePhoto(channelId: string, url: string, caption: string, at: Date) {
  const c = await credentials(channelId);
  return graph(c, `${c.account_id_on_meta}/photos`, {
    url,
    caption,
    published: false,
    scheduled_publish_time: Math.floor(at.getTime() / 1000), // 10 minutes to 30 days ahead
  });
}

How do you post to LinkedIn and upload to YouTube from Node.js?

LinkedIn wants two headers beyond the bearer token on every call: LinkedIn-Version, with the YYYYMM value easyCoexistence returns in required_headers, and X-Restli-Protocol-Version set to 2.0.0. A post is a POST to /rest/posts with the author URN, the text as commentary, PUBLIC visibility, the main feed as distribution and lifecycleState PUBLISHED. LinkedIn answers 201 and puts the new post's URN in the x-restli-id header, and any URN placed in a URL path must be URL-encoded.

YouTube takes two requests. A POST to the upload endpoint with uploadType=resumable and part=snippet,status sends the metadata and returns the session address in its Location header; a PUT of the file's bytes to that address returns the video resource with its id. Uploading as private with a publishAt date leaves the publishing to YouTube's own scheduler, so nothing of yours has to run at that hour.

Publish on LinkedIn and schedule a YouTube upload
import { readFile } from "node:fs/promises";

export async function postOnLinkedIn(channelId: string, text: string) {
  const c = await credentials(channelId);
  const r = await fetch(`${c.api_base}/posts`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${c.access_token}`,
      "LinkedIn-Version": c.required_headers["LinkedIn-Version"],
      "X-Restli-Protocol-Version": "2.0.0",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      author: c.author_urn, // urn:li:organization:... or urn:li:person:...
      commentary: text,
      visibility: "PUBLIC",
      distribution: { feedDistribution: "MAIN_FEED", targetEntities: [], thirdPartyDistributionChannels: [] },
      lifecycleState: "PUBLISHED",
      isReshareDisabledByAuthor: false,
    }),
  });
  if (r.status !== 201) throw new Error(`LinkedIn ${r.status}: ${await r.text()}`);
  return r.headers.get("x-restli-id"); // the new post's URN
}

export async function scheduleOnYouTube(channelId: string, file: string, title: string, publishAt: string) {
  const c = await credentials(channelId);
  const auth = { Authorization: `Bearer ${c.access_token}` };
  const start = await fetch(
    "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status",
    {
      method: "POST",
      headers: { ...auth, "Content-Type": "application/json; charset=UTF-8", "X-Upload-Content-Type": "video/mp4" },
      body: JSON.stringify({
        snippet: { title },
        status: { privacyStatus: "private", publishAt, selfDeclaredMadeForKids: false },
      }),
    },
  );
  const session = start.headers.get("location");
  if (!start.ok || !session) throw new Error(`YouTube ${start.status}: ${await start.text()}`);
  const done = await fetch(session, {
    method: "PUT",
    headers: { ...auth, "Content-Type": "video/mp4" },
    body: await readFile(file),
  });
  const video = (await done.json()) as { id: string };
  return video.id;
}

How do you receive comments and DMs in a Node.js route?

Each channel forwards to the URL you give PUT /channels/{id}/webhook, and that call returns the channel's signing_secret once. Every delivery is a POST of platform, account_id, external_id and entry, with an X-EC-Signature header shaped t=<unix>,v1=<hex>, where v1 is the HMAC-SHA256 of t, a dot and the raw body. Take the body as text before parsing it, reject a t older than five minutes and compare with timingSafeEqual.

For Instagram and Facebook, entry is Meta's webhook entry as Meta sent it: changes for comments and mentions, messaging for DMs. For TikTok it holds the comment.update event, which TikTok fires within five minutes of a comment, with comment_id and video_id as strings so JavaScript cannot round those 64-bit numbers. There is one attempt per event and no stored copy, so answer 204 at once and process from a queue.

Turn on forwarding and verify X-EC-Signature in a route handler
import { createHmac, timingSafeEqual } from "node:crypto";

const secrets = new Map<string, string>(); // channel id -> signing_secret, kept in your database

export async function forwardEvents(channelId: string, url: string) {
  const r = await fetch(`${EC}/channels/${channelId}/webhook`, {
    method: "PUT",
    headers: { ...KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ url }),
  });
  const body = (await r.json()) as { signing_secret: string; error?: { message: string } };
  if (!r.ok) throw new Error(body.error?.message);
  secrets.set(channelId, body.signing_secret); // returned only this once
}

function verify(raw: string, header: string | null, secret: string): boolean {
  const parts = Object.fromEntries((header ?? "").split(",").map((kv) => kv.split("=", 2)));
  const t: string = parts.t ?? "";
  const v1: string = parts.v1 ?? "";
  if (!/^[0-9]+$/.test(t) || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const mac = createHmac("sha256", secret).update(`${t}.${raw}`).digest("hex");
  return mac.length === v1.length && timingSafeEqual(Buffer.from(mac), Buffer.from(v1));
}

// POST /hooks/social as a web-standard handler (Next.js, Hono, Bun and others)
export async function POST(req: Request) {
  const raw = await req.text(); // the signature covers these exact bytes
  const event = JSON.parse(raw); // { platform, account_id, external_id, entry }
  const secret = secrets.get(event.account_id);
  if (!secret || !verify(raw, req.headers.get("x-ec-signature"), secret)) {
    return new Response("invalid signature", { status: 401 });
  }
  await enqueue(event); // one attempt per event and no retries: acknowledge first
  return new Response(null, { status: 204 });
}

How do you reply to comments and DMs from Node.js?

With a fresh credentials call and the ids in the event. On Instagram and Facebook, a DM reply goes to /{account-id}/messages, using account_id_on_meta, with the sender's id as recipient and inside 24 hours of their last message; a Page adds messaging_type RESPONSE, and Instagram allows at most 1,000 bytes of text. A comment gets a public reply, at /{comment-id}/replies on Instagram or /{comment-id}/comments on Facebook, or one private reply within 7 days.

TikTok conversations stay public, because there are no DMs on TikTok. business/comment/reply/create/, with the Access-Token header, business_id, video_id and comment_id, posts a reply of up to 1,200 characters. Read the code field of the answer, where 0 means success, rather than the HTTP status. Act only on comment_action insert with comment_type comment, because your own replies arrive as events too.

Reply to a TikTok comment and a Messenger DM
export async function reply(event: any, text: string) {
  const c = await credentials(event.account_id);
  if (event.platform === "tiktok") {
    const e = event.entry.content; // the comment.update event, ids as strings
    if (e.comment_action !== "insert" || e.comment_type !== "comment") return; // your replies arrive as "reply"
    const r = await fetch(`${c.api_base}/business/comment/reply/create/`, {
      method: "POST",
      headers: { "Access-Token": c.access_token, "Content-Type": "application/json" },
      body: JSON.stringify({ business_id: c.business_id, video_id: e.video_id, comment_id: e.comment_id, text }),
    });
    const out = (await r.json()) as { code: number; message: string };
    if (out.code !== 0) throw new Error(out.message); // 0 is success, whatever the HTTP status
  } else if (event.platform === "facebook") {
    for (const m of event.entry.messaging ?? []) {
      if (!m.message || m.message.is_echo) continue; // only what people sent the Page
      await graph(c, `${c.account_id_on_meta}/messages`, {
        recipient: { id: m.sender.id },
        messaging_type: "RESPONSE", // within 24 hours of their last message
        message: { text },
      });
    }
  }
}

How do you post to TikTok and give a TypeScript agent these tools?

Both go through easyCoexistence's MCP server at https://easycoexistence.com/api/mcp, which accepts OAuth 2.1 only: dynamic client registration, an authorization code with PKCE, access tokens that last an hour and refresh tokens. With @modelcontextprotocol/client, the official TypeScript SDK for Node 20 and later, an OAuthClientProvider holds the client, the tokens and the PKCE verifier; the first connect sends the user to sign in and throws UnauthorizedError, and finishAuth with the callback's query completes it.

TikTok publishing lives here because TikTok downloads media only from URL prefixes verified for the developer app behind the token. publish_tiktok_post takes your HTTPS link and gives TikTok a signed address on easyCoexistence's verified media route, and get_tiktok_publish_status follows the post. The same client hands an agent every tool for the account's networks; call list_social_accounts first, whose account_id is the Partner API's channel id.

Sign in over OAuth and publish to TikTok with the MCP client
import { createInterface } from "node:readline/promises";
import { Client, StreamableHTTPClientTransport, UnauthorizedError, type OAuthClientProvider } from "@modelcontextprotocol/client";

const MCP = new URL("https://easycoexistence.com/api/mcp");
const saved: Record<string, any> = {}; // persist this, so the browser sign-in happens once

const provider: OAuthClientProvider = {
  redirectUrl: "http://localhost:8090/callback",
  clientMetadata: { client_name: "My social agent", redirect_uris: ["http://localhost:8090/callback"] },
  state: () => (saved.state = crypto.randomUUID()),
  clientInformation: () => saved.client,
  saveClientInformation: (info) => { saved.client = info; },
  tokens: () => saved.tokens,
  saveTokens: (tokens) => { saved.tokens = tokens; },
  saveCodeVerifier: (verifier) => { saved.verifier = verifier; },
  codeVerifier: () => saved.verifier,
  redirectToAuthorization: (url) => console.log("Sign in to easyCoexistence:", url.href),
};

const client = new Client({ name: "my-social-agent", version: "1.0.0" });
const transport = new StreamableHTTPClientTransport(MCP, { authProvider: provider });
try {
  await client.connect(transport);
} catch (error) {
  if (!(error instanceof UnauthorizedError)) throw error;
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  const back = new URL(await rl.question("Paste the address you were sent back to: ")).searchParams;
  rl.close();
  if (back.get("state") !== saved.state) throw new Error("state mismatch");
  await transport.finishAuth(back);
  await client.connect(new StreamableHTTPClientTransport(MCP, { authProvider: provider }));
}

const result = await client.callTool({
  name: "publish_tiktok_post",
  arguments: {
    account_id: process.env.TIKTOK_CHANNEL_ID, // the Partner API channel id
    video_url: "https://cdn.example.com/launch.mp4",
    caption: "New drop #behindthescenes",
  },
});
console.log(result.content); // a share_id to follow with get_tiktok_publish_status

Common mistakes

  • Computing the HMAC over parsed and re-serialised JSON. The signature covers the raw body byte for byte, so call req.text() first and parse afterwards, or every delivery fails the check.
  • Turning TikTok ids into numbers. Comment and video ids are 64-bit and Number() rounds them, so keep the strings the event carries when you reply or look a comment up.
  • Keeping only the channel_id from the redirect. A Facebook or LinkedIn sign-in can add several Pages at once, so list them with GET /channels?external_ref= and store each one.
  • Replying to a Messenger or Instagram DM from a nightly batch. Outside 24 hours of the person's last message the send fails, so reply from the event handler while the window is open.
Doing this with EasyCoexistence

easyCoexistence gives Node.js backends and AI agents reach to customers on WhatsApp, Instagram, Facebook, TikTok, YouTube, LinkedIn and more channels, each through its official API. Connect accounts with the Partner API, fetch fresh tokens and signed events, and let TypeScript agents act through the MCP server, with every connection monitored 24/7. US$ 9 to US$ 0.75 per connection per month, falling as you add connections, with the first 3 days free.

easyCoexistence is a multichannel API and MCP server that connects AI agents such as Claude and ChatGPT to WhatsApp, Instagram, TikTok, Facebook and more. On WhatsApp it uses Coexistence: the business keeps using its number in the WhatsApp Business app while the AI works through Meta's official API.

Frequently asked questions

Do I need an SDK to call these APIs from Node?

No. The Partner API and the networks' APIs are plain HTTPS, so the global fetch in Node 18 and later covers them. @modelcontextprotocol/client comes in only for the MCP tools, TikTok publishing among them.

Why does TikTok publishing go through the MCP server?

TikTok downloads videos and photos only from a domain or URL prefix verified for the developer app, and that app is easyCoexistence's. publish_tiktok_post serves your HTTPS file from that verified address, so your own domain needs no verification.

Can one sign-in connect several Facebook or LinkedIn Pages?

Yes. Each Page, and on LinkedIn the member's own profile, becomes its own channel and its own connection. The redirect carries the first channel_id, and GET /channels?external_ref= lists them all.

How much does easyCoexistence cost for Node.js?

US$ 9 to US$ 0.75 per connection per month, falling as you add connections, and the same on every network. The Partner API and the MCP connector come with it, with no seats, and the first 3 days are free.

Keep reading

Connect your first channel in two minutes.

No platform reviews to wait for. Connect WhatsApp, Instagram, TikTok or another channel, then ask your AI to post, reply or report, and watch it work.

  • 3 days free
  • Cancel any time
  • Official APIs only
  • Monitored 24/7

Verified on