Back to blog
Creator Guidesnestjssocial-mediabackendapi-design

Building a Multi-Platform Social Media Aggregator with NestJS

By OmniPost·· 8 min read
Building a Multi-Platform Social Media Aggregator with NestJS

Every social platform is a walled garden with its own API design choices, authentication requirements, and data shapes. YouTube returns duration in ISO 8601 format inside a nested contentDetails object. Instagram wraps timestamps differently and gates media uploads behind a two-step container flow. TikTok throttles at the endpoint level rather than the application level. When you are building a product that needs to talk to all of them at once, the naive approach — one HTTP call per platform, stitched together in a single controller — breaks down fast. NestJS gives you the architectural primitives to handle this cleanly: a module system that enforces clear boundaries, dependency injection that makes platform adapters swappable, and TypeScript that catches shape mismatches between third-party responses before they reach production.

Why NestJS fits the aggregation problem

The core reason NestJS works well for a social media aggregator is that the platform boundary problem maps directly to NestJS modules. Each social network is a self-contained domain with its own auth flow, rate limits, and data model. NestJS modules are self-contained units with their own providers and exports. The correspondence is not accidental — it reflects how you actually want to think about the problem. Instagram's token refresh logic should live in an InstagramModule, isolated from everything else. When Instagram changes their refresh flow (and they will), you update one module, not a sprawling service class. Dependency injection then lets you test each platform module in complete isolation by swapping the real HTTP client for a mock, and swap a test double for the real adapter in any downstream module that depends on it.

The adapter pattern: one interface, many platforms

The most important architectural decision you will make is defining a platform adapter interface before you write a single API call. Every platform — YouTube, Instagram, TikTok, LinkedIn — must implement the same contract. This forces you to think carefully about what operations the rest of the app actually needs, rather than exposing every quirk of each platform's API surface. The adapter becomes the translation layer between the chaotic reality of third-party APIs and the clean domain model your application works with internally. Once the interface is stable, you can add a new platform by creating a new adapter class — nothing in the rest of the codebase changes.

  • publish(content: UnifiedPost): Promise<PlatformResult> — translate and submit content to the platform
  • getAnalytics(postId: string): Promise<UnifiedAnalytics> — fetch normalized performance data
  • refreshToken(userId: string): Promise<TokenPair> — renew credentials before they expire
  • validateConnection(userId: string): Promise<ConnectionStatus> — confirm the account is still connected
  • getProfile(userId: string): Promise<PlatformProfile> — retrieve basic account metadata

Module structure that maps to business logic

Once the adapter interface is defined, the module structure falls out naturally. One module per platform owns the adapter implementation and exposes it through a shared injection token so the rest of the app depends on the interface, not the concrete class. A ContentModule handles the unified content model — creating drafts, scheduling posts, and tracking state across platforms. A SchedulerModule processes queued publishing jobs without blocking the HTTP request cycle. A TokenModule manages the encrypted credential store and refresh lifecycle across all connected accounts. Keeping these boundaries clean means new features stay in the right module, and the blast radius of a third-party API change stays small.

  • YouTubeModule, InstagramModule — one per platform, each owns its adapter and HTTP client
  • ContentModule — unified post model, draft management, cross-platform publish orchestration
  • SchedulerModule — BullMQ job queue for delayed and recurring publishing
  • TokenModule — encrypted credential storage, expiry tracking, and silent refresh
  • AnalyticsModule — normalized performance metrics aggregated across platforms

Taming OAuth2 across multiple providers

OAuth2 across multiple providers is where most aggregator projects hit their first serious production pain. Every platform issues tokens with different expiry windows and different refresh mechanics. Instagram long-lived tokens expire in 60 days and must be refreshed before the window closes — miss it and the user must reconnect manually. YouTube access tokens expire in one hour but refresh silently using a refresh token that does not expire. TikTok uses a separate client credentials flow for analytics. A TokenService that wraps all of this behind a single getValidToken(userId, platform) method keeps the complexity out of your adapters. The service checks the stored expiry, refreshes if needed, updates the encrypted store, and returns a valid token. Adapters never touch the OAuth endpoints directly — they ask the TokenService for a token and trust it to return something usable.

Rate limiting: respect the platforms, protect your app

Rate limiting is the second place aggregators typically break in production. Each platform enforces limits at different granularities — Instagram caps at 200 API calls per user per hour, YouTube's Data API measures consumption in quota units per day rather than raw call counts, TikTok enforces both per-minute and per-day limits simultaneously. A naive approach — letting the HTTP client fail on 429s and retrying immediately — produces a storm of failed requests during peak scheduling windows. The better pattern is a per-platform job queue: publishing jobs enter the queue, and a per-platform worker drains the queue at the rate each platform tolerates. The scheduler enqueues a job and returns immediately; the worker owns the timing. Exponential backoff with jitter handles the transient failures that still slip through.

  • Instagram: token bucket at 200 requests per hour per connected account — track remaining budget per user
  • YouTube: track daily quota units consumed and reserve capacity for publishing over read-only analytics calls
  • TikTok: enforce both per-minute and per-day limits at the queue worker level, not the HTTP client level
  • All platforms: exponential backoff (1s → 2s → 4s → 8s) with random jitter to prevent synchronized retries across users

Normalizing the content model

Platforms disagree fundamentally on what a post is. YouTube requires a title, description, privacy setting, category ID, and video file. Instagram requires a media container ID to be created first, then a second API call to publish it with a caption. TikTok has its own chunked upload flow with separate initialization and completion calls. If you model each platform's native shape in your domain layer, your ContentModule becomes a mapping maze that changes every time a platform updates their API. The solution is a UnifiedPost type that captures the creator's intent — text, media references, platform-specific overrides, target platforms, and scheduled time — and let each adapter silently translate it into the native API call. The creator writes a caption once and selects their platforms. The adapters do the translating. The domain model never changes shape because a platform does.

Graceful degradation when a platform goes down

The last architectural piece that separates production-grade aggregators from demos is graceful degradation. When Instagram returns a 503, publishing to YouTube should still work. When TikTok's API is slow, it should not block the Instagram response. NestJS exception filters combined with a per-adapter circuit breaker isolate failures to the affected platform. The circuit breaker opens after a configurable number of consecutive failures and immediately returns a known error state instead of waiting for timeouts to accumulate. The user sees a per-platform status — "Instagram temporarily unavailable, your post is queued for retry" — not a generic error that wipes out the entire publishing flow. Partial availability is almost always better than total failure, and it is achievable with a few well-placed abstractions.

Putting it all together

The adapter interface, one module per platform, a unified content model, a job queue for rate limiting, and per-adapter circuit breakers — this is the architecture that lets a single NestJS backend reliably talk to five or six social platforms at once without the whole system going down when one of them misbehaves. The module boundaries are clean enough that adding a new platform means creating a new module, not touching existing logic. The TypeScript types at the adapter interface catch the shape mismatches that third-party APIs introduce constantly. The job queue decouples the user-facing scheduling action from the actual API call, so scheduling feels instant even when a downstream platform is slow. This is the architecture behind OmniPost — built this way from the start because retrofitting these patterns onto a tangled codebase is far more expensive than starting with clean boundaries.

Your next video has more content inside it.

Let OmniPost find it, adapt it, and publish it.
No credit card required