npm.io
1.2.1 • Published 5m ago

social-bridge-sdk

Licence
MIT
Version
1.2.1
Deps
1
Size
77 kB
Vulns
0
Weekly
0

Social Bridge SDK

One SDK. Every platform. Zero boilerplate.

A lightweight, type-safe, production-ready Node.js SDK that unifies content publishing across Facebook, Instagram, Threads, LinkedIn, TikTok, and X (Twitter) — so you stop rewriting the same API glue code for every platform.

npm version License: MIT Node.js TypeScript


Currently supported for publishing: Facebook, Instagram, Threads, LinkedIn, TikTok, and X (Twitter — text posts).

Not yet available (planned, see Roadmap): X media posts, Instagram Reels/Stories, YouTube Shorts, Telegram, Pinterest, Discord, Mastodon, Reddit, Google Business Profile, and a separate WhatsApp module for inbound messaging and auto-reply bots. If you came here looking for one of these, they are not implemented yet — please check the Roadmap section below for current status.


The Problem

If you've ever built a social media scheduler, a marketing automation tool, or simply a script to cross-post content, you already know the pain:

  • Facebook wants multipart params on /feed or /photos.
  • Instagram forces you into a two-step container → publish dance.
  • Threads mirrors that same two-step flow, but on a completely different host.
  • LinkedIn wants a raw JSON body, a different auth header style, and hides the post ID inside a response header instead of the body.
  • TikTok requires you to query the creator's allowed privacy levels before every publish, then run a separate init → async publish flow that's different again for videos vs. photo carousels.
  • X (Twitter) only accepts user-context OAuth tokens — there's no simple app token, and its media pipeline is a completely separate chunked upload flow from the one used to actually create the post.

Every platform has its own quirks, its own error shapes, and its own authentication model. Multiply that by every project you build, and you're maintaining the same fragile glue code over and over.

Social Bridge SDK solves this by giving you one consistent interface: same method signature, same success/error shape, same import — regardless of which platform you're posting to.


Features

  • Unified APIpublishToFacebook(), publishToInstagram(), publishToThreads(), publishToLinkedIn(), publishToTikTok(), and publishToTwitter() all share the same PostContent input shape.
  • Security-first — credentials are never hardcoded; the SDK reads from process.env or an explicit config object you control.
  • Predictable error handling — every method resolves (never throws) with a typed { success: true/false, ... } object. No more wrapping every call in try/catch.
  • Lightweight — a single runtime dependency (axios). No heavy frameworks, no bloated abstractions.
  • Fully typed — written in TypeScript with strict mode enabled, shipped with .d.ts declaration files.
  • Multi-post helperpublishToAll() fans a single piece of content out to multiple platforms concurrently.
  • ESM native — modern import syntax, tree-shakeable, Node.js 18+.

Installation

npm install social-bridge-sdk

Quick Start

1. Set up your environment variables

Create a .env file in your project root (see .env.example in this repo for the full template):

FACEBOOK_PAGE_ID=your_page_id
FACEBOOK_PAGE_ACCESS_TOKEN=your_page_access_token

INSTAGRAM_BUSINESS_ACCOUNT_ID=your_ig_business_account_id
INSTAGRAM_ACCESS_TOKEN=your_ig_access_token

THREADS_USER_ID=your_threads_user_id
THREADS_ACCESS_TOKEN=your_threads_access_token

LINKEDIN_AUTHOR_URN=urn:li:organization:12345678
LINKEDIN_ACCESS_TOKEN=your_linkedin_access_token

TIKTOK_ACCESS_TOKEN=your_tiktok_access_token
TIKTOK_PRIVACY_LEVEL=SELF_ONLY

TWITTER_ACCESS_TOKEN=your_x_user_context_access_token

Load them with dotenv (import 'dotenv/config') or your framework's built-in env loader.

2. Publish content
import { SocialBridge } from 'social-bridge-sdk';

// With no arguments, SocialBridge reads all credentials from process.env
const bridge = new SocialBridge();

const result = await bridge.publishToFacebook({
  text: 'Launching our new product today! 🚀',
  imageUrl: 'https://example.com/images/launch-banner.png',
});

if (result.success) {
  console.log(`✅ Posted to Facebook! Post ID: ${result.postId}`);
} else {
  console.error(`❌ Failed to post: ${result.message}`);
}

Usage per Platform

Facebook
const result = await bridge.publishToFacebook({
  text: 'Hello from Social Bridge SDK!',
  imageUrl: 'https://example.com/photo.jpg', // optional — omit for a text-only post
});
Instagram

Instagram's Graph API requires an image for every post — text-only posts are not supported by the platform itself.

const result = await bridge.publishToInstagram({
  text: 'New drop available now 🔥',
  imageUrl: 'https://example.com/product.jpg', // required
});
Threads
const result = await bridge.publishToThreads({
  text: 'Thoughts on the future of dev tooling 🧵',
  imageUrl: 'https://example.com/optional-image.jpg', // optional
});
LinkedIn
const result = await bridge.publishToLinkedIn({
  text: 'Excited to share our latest engineering deep-dive.',
  imageUrl: 'https://example.com/cover.jpg', // optional
});
TikTok

TikTok's Content Posting API is video-first. For a video post, pass videoUrl. For a photo carousel post, pass imageUrls (an array) instead — the SDK automatically selects the right endpoint. Both videoUrl and any URLs in imageUrls must be hosted on a domain you've verified in the TikTok Developer Portal.

Before publishing, the SDK automatically queries TikTok's creator_info endpoint to confirm your requested privacyLevel is actually allowed for the connected creator, and returns a clear error instead of a silent rejection if it isn't. If you don't set a privacy level, it safely defaults to SELF_ONLY.

// Video post
const videoResult = await bridge.publishToTikTok({
  text: 'Check out our new feature walkthrough 🎥',
  videoUrl: 'https://your-verified-domain.com/videos/demo.mp4',
});

// Photo carousel post
const photoResult = await bridge.publishToTikTok({
  text: 'Behind the scenes 📸',
  imageUrls: [
    'https://your-verified-domain.com/images/1.jpg',
    'https://your-verified-domain.com/images/2.jpg',
  ],
});

TikTok's Direct Post flow is asynchronous: a successful publishToTikTok() call means the post was accepted and queued (result.postId is the publish_id), not that it is live yet. Poll TikTok's status endpoint with that ID if you need final publish confirmation.

X (Twitter)

X's API always posts on behalf of a specific user. TWITTER_ACCESS_TOKEN must be a user-context OAuth 2.0 (PKCE) or OAuth 1.0a access token with the tweet.write scope, generated through your own OAuth flow — an app-only Bearer Token cannot create posts. This SDK does not perform the OAuth handshake; it only sends the request once you already have a valid token.

This MVP release supports text-only posts on X. Media attachments (imageUrl / videoUrl) are on the roadmap — X's media pipeline is a separate chunked upload flow unrelated to the post-creation endpoint, so it's being implemented as its own dedicated feature rather than bolted on.

const result = await bridge.publishToTwitter({
  text: 'Shipping fast with Social Bridge SDK 🚀',
});
Publish to Multiple Platforms at Once
const results = await bridge.publishToAll(
  ['facebook', 'linkedin', 'threads'],
  { text: 'Cross-posted everywhere in one call 🎯' },
);
// Note: publishToAll() sends the same PostContent to every platform, so
// only include 'tiktok' here if your content also has videoUrl/imageUrls set,
// and remember 'twitter' only publishes the `text` field for now —
// otherwise call the platform-specific method directly with tailored content.

results.forEach((r) => {
  console.log(r.success ? `${r.platform}: ${r.postId}` : `${r.platform}: ${r.message}`);
});
Passing Credentials Explicitly (instead of process.env)

Useful for multi-tenant apps where tokens come from a database rather than environment variables:

const bridge = new SocialBridge({
  facebook: {
    pageId: 'PAGE_ID_FROM_DB',
    accessToken: 'PAGE_TOKEN_FROM_DB',
  },
});

API Reference

Method Description Required Fields in content
publishToFacebook(content) Publishes a post to a Facebook Page text (image optional)
publishToInstagram(content) Publishes an image post to Instagram text, imageUrl (required)
publishToThreads(content) Publishes a post to Threads text (image optional)
publishToLinkedIn(content) Publishes a post to LinkedIn (member or organization page) text (image optional)
publishToTikTok(content) Publishes a video or photo-carousel post to TikTok videoUrl or imageUrls (required)
publishToTwitter(content) Publishes a text post to X (Twitter) text (media not yet supported)
publishToAll(platforms, content) Publishes to several platforms concurrently Depends on selected platforms

Every method resolves to a PublishResponse:

type PublishResponse =
  | { success: true; platform: string; postId: string; raw?: unknown }
  | { success: false; platform: string; message: string; details?: unknown };

Roadmap

Social Bridge SDK is actively evolving. Here's the current state, in order:

Shipped
  • Facebook Page Post API
  • Instagram Graph API (image posts)
  • Threads API
  • LinkedIn Share API (UGC Posts)
  • TikTok Content Posting API (video posts + photo carousels)
  • X (Twitter) API v2 (text posts)
Currently in development
  • X (Twitter) media posts (images/video via the chunked upload API)
Planned next (not started)
  • Instagram Reels & Stories publishing (the Graph API supports both beyond static images)
  • X (Twitter) reply threads (chaining posts via in_reply_to_tweet_id)
  • YouTube Shorts (via the YouTube Data API)
  • Telegram (Bot API — channel/group broadcasting)
  • Pinterest (REST API v5 — Pins on Boards)
  • Discord (Webhooks — rich embeds)
  • Mastodon (Statuses API)
  • Reddit (submit API — OAuth 2.0)
  • Google Business Profile (Local Posts / Offers / Events)
  • WhatsApp Module — a separate opt-in module for inbound messaging, auto-replies, and simple bots (see details below)
  • Local request validation before every call (e.g. X's 280-character limit, LinkedIn's 3,000-character limit) to fail fast without wasting an API call or rate-limit quota
  • Built-in retry/backoff strategy for 429 Too Many Requests responses
  • Media upload from local file buffers (not just hosted URLs)
  • Polling helper for TikTok's async publish status endpoint
  • Scheduled publishing helpers
Known platform limitations (not on the roadmap)

A couple of frequently-requested features are not achievable through official APIs today, so they are intentionally excluded rather than promised:

  • Facebook Groups posting — Meta fully removed group-publishing endpoints and the publish_to_groups permission from the Graph API for all third-party apps. Posting to a Facebook Group is currently only possible manually, through Facebook's own UI.
  • LinkedIn document/PDF carousel posts — LinkedIn's official Posts API does not accept document/PDF uploads as of this writing; PDF carousels can only be created through LinkedIn's own composer. This SDK will add support the moment LinkedIn exposes it via the API.
Coming Soon: WhatsApp Module (Inbound Messaging & Bots)

Every platform above is about outbound publishing — pushing a post out to a feed. The WhatsApp Module is a different kind of feature entirely, built for two-way conversation rather than one-way posting.

Planned scope (via the official WhatsApp Business Platform / Cloud API):

  • Automatic replies to incoming messages — configure trigger rules (keywords, business hours, first-contact greetings) and let the SDK respond on your behalf.
  • Simple bot/flow support — a lightweight way to define a sequence of prompts and responses (e.g. FAQ bots, order-status lookups) without pulling in a full conversational-AI framework.
  • Webhook handling helpers — utilities to verify and parse incoming WhatsApp webhook payloads (Node/Express-friendly), since that's the entry point for every inbound message.
  • Outbound template & session messages — sending approved message templates and free-form replies within the 24-hour customer service window.

This will be delivered as an opt-in module (e.g. bridge.whatsapp.*) so it doesn't add weight or new dependencies for developers who only need outbound publishing. Design discussion and early implementation will be tracked in the repository's Issues — contributions and feedback are very welcome once the module scaffold lands.

Want to help build one of these? Check out CONTRIBUTING.md — new platform integrations are one of the most valuable contributions you can make.


Contributing

Contributions are very welcome, whether it's a bug fix, a new platform integration, or a documentation improvement. Please read CONTRIBUTING.md for the full workflow, coding conventions, and a step-by-step guide on how to add a new platform to the SDK.


Security

Never commit real access tokens or .env files to version control. This SDK is designed so that no credential ever needs to live in source code — it either comes from process.env or from a config object you manage securely (e.g., a secrets manager). If you discover a security issue, please open an issue or contact the maintainers directly rather than filing a public report.


License

MIT Social Bridge SDK Contributors

Keywords