vibes.diy/docs Make an app → Discord
creator docs · reference · generated

Post as you — one draft, out to Threads, LinkedIn and Instagram

This is the same document the Vibes code generator reads when it builds apps — rendered from prompts/pkg/llms/social-post.md on every deploy, so it can't drift from what the platform actually does. Read it from your terminal any time with npx vibes-diy skills.

A post-as-you app lets each visitor connect their own Threads, LinkedIn and Instagram accounts, write one update, and send it to the networks they pick with one press. The post lands on their feed, under their own name. The platform shows the consent screen, signs them in, holds the credential, and uploads pictures where a network needs it, so the app contains no client id, secret, token field or upload code.

Signal words: "post to my LinkedIn", "share on Threads and Instagram", "cross-post", "one update to all my socials", "a composer for my social accounts", "share my sketch to Instagram".

The four parts, every time

Declare each network with its posting scope in config.connections, give each one its own Connect button from useConnection, post from a fetch route through @vibes.diy/social, and call that route from the page with apiFetch. Leave out any one and the app breaks: an undeclared network has no consent card, a missing button can never be approved, and a plain fetch("/_api/…") reaches the backend as nobody, so every post is refused.

Declare — backend.js

network scopes to declare what the post can carry
threads threads_basic, threads_content_publish text up to 500 characters, optionally one picture
linkedin profile, w_member_social text up to 3,000 characters, plus one picture or one link card
instagram instagram_business_basic, instagram_business_content_publish a picture is required, caption up to 2,200 characters

A scope that posts is a separate scope, and asking for it is the whole authorization. The visitor sees "Post to your LinkedIn feed as you" beside your why and decides; an app that declared only the read scope cannot post. Declare the read scope beside it as the table shows: LinkedIn needs profile to know who the author is, and the Threads and Instagram read scopes are how a post comes back with its link.

why is quoted to the visitor as the app's own words. Say what is posted and when: "Post your update to your Threads feed when you press Post."

Instagram connects Creator and Business accounts. A visitor with a personal account is shown how to switch (it is free, keeps their posts and followers, and can be switched back), so the app needs no extra step for it.

Connect and renew — App.jsx

Each network gets its own button, and each button follows the connection's state. useConnection(network) gives state (pending | absent | live | expiring | dead), consented, available, accountLabel and link().

Offer a Renew button while a connection is expiring. LinkedIn's sign-in lasts 60 days and cannot renew by itself: the person renews it by signing in again: they confirm the platform's connect card, and while they are still signed in to LinkedIn, LinkedIn's own screen passes straight through. So expiring shows "Connected as … · Renew", and Renew calls the same link() as Connect. A dead connection gets a Reconnect button that calls link() too. link() resolves when the sign-in starts, not when it finishes, so after it the button re-reads with refresh() every few seconds, a handful of times, while the page is in view.

Render the connected branch first: available only stops a connection being started, never one that already works.

Post — backend.js

  • threads(ctx).publish({ text, imageUrl? }) → { id, permalink? }
  • linkedin(ctx).post({ text, imageUrl?, altText?, link?, visibility? }) → { id, permalink }. text is plain prose (the library escapes LinkedIn's formatting characters and keeps #hashtags live). visibility is "PUBLIC" (default) or "CONNECTIONS". A post carries imageUrl or link, never both.
  • instagram(ctx).publish({ imageUrl, caption? }) → { id, permalink? }
  • connectionState(ctx, network) → { state: "live" | "needs_consent" | "dead" | "error" }, spending nothing. Check it before posting so an unconnected network comes back as a sentence, not a thrown error.

A picture is a public https URL that every network can fetch. Use a JPEG to post the same picture everywhere: Instagram takes JPEG only, Threads takes JPEG or PNG, and LinkedIn takes JPEG, PNG or GIF up to 8 MB. The visitor picks any photo through the photo input above, and shrinkPhoto(file, { type: "image/jpeg" }) turns it into that JPEG, location stripped. The picture is saved as a file on a record every visitor can read (its own grant.public channel in access.js), holding the picture alone (the post's words stay off it until a network has them); wait for that save's synced receipt to read "accepted", then read the record back and its _files.photo.shareUrl is the imageUrl. (url is a blob: address only this page can open until then; shareUrl is the public one.) Threads and Instagram fetch it themselves; for LinkedIn the platform uploads it for the member, so the same URL works on all three.

Post one network at a time and answer for each. A post that fails on one network still lands on the others, so the route returns one result per network — { ok: true, permalink } or { ok: false, error } — and the page shows each beside its network, with the link to the live post. A thrown error carries detail (a plain sentence, from the picture step), reason (a connection word such as needs_consent) or message; show the first one present.

Post only when the person presses the button. Posting is an act done in someone's name, so it happens in a fetch route the page calls on their press, never in a scheduled tick and never on page load. A visitor's connection can only be spent while they are there: scheduled runs as the app's owner.

Build posts from text and pictures.

A complete composer

backend.js

jsimport { threads, linkedin, instagram, connectionState } from "@vibes.diy/social";

export const config = {
  connections: [
    {
      provider: "threads",
      scopes: ["threads_basic", "threads_content_publish"],
      why: "Post your update to your Threads feed when you press Post.",
    },
    {
      provider: "linkedin",
      scopes: ["profile", "w_member_social"],
      why: "Post your update to your LinkedIn feed when you press Post.",
    },
    {
      provider: "instagram",
      scopes: ["instagram_business_basic", "instagram_business_content_publish"],
      why: "Post your photo and caption to your Instagram when you press Post.",
    },
  ],
};

const LIMITS = { threads: 500, linkedin: 3000, instagram: 2200 };

function postTo(ctx, network, text, imageUrl) {
  if (network === "threads") return threads(ctx).publish({ text, imageUrl });
  if (network === "linkedin") return linkedin(ctx).post({ text, imageUrl });
  return instagram(ctx).publish({ imageUrl, caption: text });
}

async function postEverywhere(ctx, { text, imageUrl, networks }) {
  const results = {};
  for (const network of new Set(networks)) {
    if (!(network in LIMITS)) continue;
    const conn = await connectionState(ctx, network);
    if (conn.state !== "live") {
      results[network] = { ok: false, error: conn.state === "dead" ? "Reconnect to post here." : "Connect to post here." };
    } else if (text.length > LIMITS[network]) {
      results[network] = { ok: false, error: `Keep it under ${LIMITS[network]} characters here.` };
    } else if (network === "instagram" && !imageUrl) {
      results[network] = { ok: false, error: "Add a photo to post to Instagram." };
    } else {
      try {
        const { permalink } = await postTo(ctx, network, text, imageUrl);
        results[network] = { ok: true, permalink: permalink ?? null };
      } catch (err) {
        ctx.log(`post to ${network} failed: ${err.message}`);
        results[network] = { ok: false, error: err.detail ?? err.reason ?? err.message };
      }
    }
  }
  return results;
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname.endsWith("/post") && request.method === "POST") {
    const { text = "", imageUrl, networks = [] } = await request.json();
    const results = await postEverywhere(ctx, { text, imageUrl: imageUrl || undefined, networks });
    return Response.json({ results });
  }
  return new Response("not found", { status: 404 });
}

access.js

js// The picture record is the one thing the networks read: Threads and Instagram fetch
// its file themselves, and the platform fetches it for LinkedIn. So it goes on its own
// channel that anyone can read, and it holds the picture alone.
export default function (doc, oldDoc, user) {
  if (doc.type === "picture") {
    if (!user) throw { forbidden: "Sign in to add a picture." };
    // Create-only: everyone can read it, so nobody may swap another visitor's picture.
    if (oldDoc) throw { forbidden: "A saved picture stays as it is." };
    const ch = `picture:${doc._id}`;
    return { channels: [ch], grant: { public: [ch] } };
  }
  throw { forbidden: "unknown record type" };
}

App.jsx

jsximport React, { useRef, useState } from "react";
import { useFireproof } from "use-fireproof";
import { useConnection, apiFetch } from "use-vibes";
import { Badge, Button, Card, ErrorNote, Field, Heading, Row, Stack, Text, Textarea } from "@vibes.diy/ui";
import { shrinkPhoto } from "./lib/photos.js";

const NETWORKS = [
  { id: "threads", name: "Threads", limit: 500 },
  { id: "linkedin", name: "LinkedIn", limit: 3000 },
  { id: "instagram", name: "Instagram", limit: 2200 },
];

// Resolves when the server has answered for this save: "accepted", "refused" or "held".
function whenSettled(synced) {
  return new Promise((resolve) => synced.on((s) => s.status !== "pending" && resolve(s)));
}

function NetworkRow({ network, picked, onPick, result }) {
  const { state, consented, available, accountLabel, link, refresh } = useConnection(network.id);
  // link() resolves when sign-in STARTS, so re-read a few times while the page is in view.
  async function connect() {
    await link();
    for (let i = 0; i < 6; i++) {
      await new Promise((r) => setTimeout(r, 3000));
      if (document.visibilityState === "visible") await refresh();
    }
  }
  if (state === "pending") return null;
  const connected = consented && (state === "live" || state === "expiring");
  return (
    <Row gap={2} align="center" wrap>
      <Text>{network.name}</Text>
      {connected ? (
        <>
          <Button type="button" variant={picked ? "primary" : "quiet"} onClick={() => onPick(!picked)}>
            {picked ? "Posting here" : `Post as ${accountLabel}`}
          </Button>
          {state === "expiring" && (
            <Button type="button" variant="quiet" onClick={connect}>
              Renew
            </Button>
          )}
        </>
      ) : !available ? (
        <Text muted>Connecting {network.name} opens up again soon.</Text>
      ) : (
        <Button type="button" onClick={connect}>
          {state === "dead" ? `Reconnect ${network.name}` : `Connect ${network.name}`}
        </Button>
      )}
      {result?.ok && (result.permalink ? <a href={result.permalink} target="_blank" rel="noreferrer">See the post</a> : <Badge tone="up">Posted</Badge>)}
      {result && !result.ok && <Text muted>{result.error}</Text>}
    </Row>
  );
}

export default function App() {
  const { database } = useFireproof("posts");
  const [text, setText] = useState("");
  const [photo, setPhoto] = useState(null);
  const [picked, setPicked] = useState({});
  const [results, setResults] = useState({});
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState("");
  const fileRef = useRef(null);
  const [photoUrl, setPhotoUrl] = useState("");
  const pickPhoto = (file) => {
    if (photoUrl) URL.revokeObjectURL(photoUrl);
    setPhoto(file);
    setPhotoUrl(file ? URL.createObjectURL(file) : "");
  };

  const networks = NETWORKS.filter((n) => picked[n.id]).map((n) => n.id);
  // Instagram takes a photo with no caption; every other network needs words.
  const ready = text.trim() !== "" || (photo !== null && networks.every((n) => n === "instagram"));
  const editDraft = (next) => {
    setText(next);
    setResults({});
  };

  async function post() {
    setBusy(true);
    setProblem("");
    setResults({});
    try {
      let imageUrl;
      if (photo) {
        // The picture alone lives on a record every visitor can read, so each network can fetch it.
        const saved = await database.put({ type: "picture", createdAt: Date.now(), _files: { photo } });
        const receipt = await whenSettled(saved.synced);
        if (receipt.status !== "accepted") {
          setProblem(receipt.message || "Sign in to post your photo.");
          return;
        }
        const doc = await database.get(saved.id);
        imageUrl = doc._files.photo.shareUrl;
      }
      const res = await apiFetch("/post", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ text, imageUrl, networks }),
      });
      const data = await res.json();
      if (res.ok) setResults(data.results);
      else setProblem("The post did not go out. Try again in a moment.");
    } catch (err) {
      setProblem(err.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="min-h-screen p-6 max-w-xl mx-auto bg-background text-foreground font-sans">
      <Stack gap={4}>
        <Heading level={1}>Post as you</Heading>
        <Card>
          <Stack gap={3}>
            <Field label="Your update">
              {(id, describedBy) => <Textarea id={id} describedBy={describedBy} rows={5} value={text} onChange={editDraft} />}
            </Field>
            <Text muted size="sm">{text.length} characters</Text>
            <Row gap={3} align="center">
              <Button type="button" variant="quiet" onClick={() => fileRef.current?.click()}>
                {photo ? "Pick a different photo" : "Add a photo"}
              </Button>
              {photo && <img src={photoUrl} alt="Your photo" className="h-16 w-16 rounded-md object-cover" />}
              {photo && <Button type="button" variant="quiet" onClick={() => pickPhoto(null)}>Remove</Button>}
            </Row>
            {/* Any photo from the camera or library; shrinkPhoto hands Instagram the JPEG it needs, location stripped. */}
            <input ref={fileRef} type="file" accept="image/*" hidden
              onChange={async (e) => {
                const f = e.target.files?.[0];
                e.target.value = "";
                if (!f) return;
                const jpeg = await shrinkPhoto(f, { type: "image/jpeg" });
                if (jpeg) pickPhoto(jpeg);
                else setProblem("That picture didn't open here. Try a JPEG or PNG.");
              }} />
          </Stack>
        </Card>
        <Stack gap={2}>
          {NETWORKS.map((n) => (
            <NetworkRow
              key={n.id}
              network={n}
              picked={!!picked[n.id]}
              onPick={(on) => setPicked((p) => ({ ...p, [n.id]: on }))}
              result={results[n.id]}
            />
          ))}
        </Stack>
        <Button type="button" size="lg" disabled={busy || networks.length === 0 || !ready} onClick={post}>
          {busy ? "Posting…" : `Post to ${networks.length || "your"} ${networks.length === 1 ? "network" : "networks"}`}
        </Button>
        {problem && <ErrorNote>{problem}</ErrorNote>}
      </Stack>
    </div>
  );
}

Building it well

  • One draft, many networks: show each network's character count against its own limit, and say before the press that Instagram needs a photo.
  • A network the visitor has not connected shows its Connect button in place; the rest of the composer keeps working.
  • Keep the post's text exactly as written. Hashtags work everywhere; an @-mention is plain text on LinkedIn.
  • Save what was posted (text, picture, the per-network links) once it has posted, as a record the visitor reads, so they can see their history. Give it its own arm in access.js on the visitor's own channel, apart from the public picture.
  • A visitor's account is never a pasted token or a ctx.secrets value, and the app never builds an Authorization header: the platform attaches the credential.