Supabase
Schedule social media posts from a row in your Supabase database, with a Database Webhook, two Edge Functions and the Fuxux API.
Insert a row in Postgres and it becomes a social post in Fuxux. Use it to announce releases, blog posts, products or listings from data you already keep in Supabase. When the post goes out or fails, the row is updated with the result.
How it works
- Your app inserts a row in
social_posts. - A Supabase Database Webhook calls the
fuxux-sendEdge Function. - The function creates the post through the Fuxux API: a draft if the row has no
scheduled_at, otherwise a scheduled post. It never publishes at once. - When the post finishes, Fuxux calls the
fuxux-webhookfunction, which checks the signature and writes the result to the row.
What you need
- A Supabase project (the free plan works) and the Supabase CLI, linked to the project.
- A paid Fuxux plan (Creator, Growth or Pro), which includes API keys and webhooks, with at least one social account connected.
1. Create the table
Run this in the SQL Editor:
create table public.social_posts (
id uuid primary key default gen_random_uuid(),
-- Platform id to caption, for example {"linkedin": "We shipped v2"}
captions jsonb not null,
-- Public https URLs, at most 4
media_urls text[] not null default '{}',
-- Empty: saved as a draft in Fuxux. Set: scheduled for that time.
scheduled_at timestamptz,
status text not null default 'queued' check (status in (
'queued', 'sending', 'draft', 'scheduled',
'published', 'partially_failed', 'failed', 'error'
)),
fuxux_post_id text unique,
failed_platforms text[] not null default '{}',
published_at timestamptz,
error text,
created_at timestamptz not null default now()
);
-- No policies: only your server code and these functions can reach the table.
alter table public.social_posts enable row level security;2. Add the two functions
supabase functions new fuxux-send supabase functions new fuxux-webhook # Paste the code below into each function's index.ts, then: supabase functions deploy fuxux-send --no-verify-jwt supabase functions deploy fuxux-webhook --no-verify-jwt
--no-verify-jwt is needed because neither caller sends a Supabase token. Each function checks its own secret instead.
supabase/functions/fuxux-send/index.ts
import { createClient } from "jsr:@supabase/supabase-js@2";
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
function sameText(a: string, b: string) {
if (!a || a.length !== b.length) return false;
let difference = 0;
for (let i = 0; i < a.length; i++) difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
return difference === 0;
}
const reply = (status: number, message: string) =>
new Response(JSON.stringify({ message }), {
status,
headers: { "Content-Type": "application/json" },
});
Deno.serve(async (req) => {
const secret = Deno.env.get("DB_WEBHOOK_SECRET") ?? "";
if (!sameText(req.headers.get("x-webhook-secret") ?? "", secret)) {
return reply(401, "Wrong webhook secret");
}
const { record } = await req.json();
if (record?.status !== "queued") return reply(200, "Nothing to send");
// Only one call can move a row from queued to sending.
const { data: row, error: claimError } = await supabase
.from("social_posts")
.update({ status: "sending", error: null })
.eq("id", record.id)
.eq("status", "queued")
.select()
.maybeSingle();
if (claimError) return reply(500, claimError.message);
if (!row) return reply(200, "Already taken");
const post: Record<string, unknown> = { captions: row.captions };
if (row.media_urls?.length) post.media_urls = row.media_urls;
// This recipe never publishes at once: no date means a draft.
if (row.scheduled_at) post.scheduled_at = new Date(row.scheduled_at).toISOString();
else post.draft = true;
let update: Record<string, unknown>;
try {
const res = await fetch("https://www.fuxux.com/api/posts", {
method: "POST",
headers: {
Authorization: "Bearer " + Deno.env.get("FUXUX_API_KEY"),
"Content-Type": "application/json",
// Sending the same row again cannot create a second post.
"Idempotency-Key": row.id,
},
body: JSON.stringify(post),
signal: AbortSignal.timeout(20000),
});
const body = await res.json().catch(() => ({}));
if (res.ok && body.post?.id) {
const known = ["draft", "scheduled", "published", "failed"];
update = {
status: known.includes(body.post.status) ? body.post.status : "scheduled",
fuxux_post_id: body.post.id,
// Parts Fuxux could not use, such as a network with no connected account.
error: body.skipped?.length
? body.skipped.map((item: { message: string }) => item.message).join("; ")
: null,
};
} else {
update = { status: "error", error: body.error ?? "Fuxux answered " + res.status };
}
} catch (e) {
update = { status: "error", error: e instanceof Error ? e.message : String(e) };
}
const { error: saveError } = await supabase
.from("social_posts")
.update(update)
.eq("id", row.id);
if (saveError) return reply(500, saveError.message);
return reply(200, "Done");
});supabase/functions/fuxux-webhook/index.ts
import { createClient } from "jsr:@supabase/supabase-js@2";
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
async function validSignature(rawBody: string, header: string | null) {
const match = /^sha256=([0-9a-f]{64})$/.exec(header ?? "");
const secret = Deno.env.get("FUXUX_WEBHOOK_SECRET");
if (!match || !secret) return false;
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"],
);
const signature = Uint8Array.from(
match[1].match(/../g)!.map((byte) => parseInt(byte, 16)),
);
return crypto.subtle.verify("HMAC", key, signature, encoder.encode(rawBody));
}
Deno.serve(async (req) => {
// Check the exact bytes Fuxux signed, before parsing them.
const rawBody = await req.text();
if (!(await validSignature(rawBody, req.headers.get("x-fuxux-signature")))) {
return new Response("Bad signature", { status: 401 });
}
const event = JSON.parse(rawBody);
if (event.event !== "post.finished") return new Response("Ignored");
const failures = (event.results ?? [])
.filter((result: { success: boolean }) => !result.success)
.map((result: { platform: string; error: string | null }) =>
result.platform + ": " + (result.error ?? "failed")
);
// A post that did not come from this table matches no row and changes nothing.
const { error } = await supabase
.from("social_posts")
.update({
status: event.outcome,
published_at: event.published_at,
failed_platforms: event.failed_platforms ?? [],
error: failures.length ? failures.join("; ") : null,
})
.eq("fuxux_post_id", event.post_id);
// A 5xx makes Fuxux send this event again later.
if (error) return new Response(error.message, { status: 500 });
return new Response("OK");
});3. Connect Fuxux
On the API keys page in Fuxux, create a key for this integration. Set the webhook URL to https://<project-ref>.supabase.co/functions/v1/fuxux-webhook and copy the signing secret.
A Fuxux account has one webhook URL, and it receives every post on the account. If you already use one, replacing it stops those deliveries. Posts that didn't come from this table are ignored by the function.
# Make a random value for DB_WEBHOOK_SECRET and keep it for the next step openssl rand -hex 32 supabase secrets set \ FUXUX_API_KEY=fx_live_your_key_here \ FUXUX_WEBHOOK_SECRET=your_fuxux_signing_secret \ DB_WEBHOOK_SECRET=the_random_value
4. Create the Database Webhook
- In the Supabase dashboard, open Database, then Webhooks, and create a webhook.
- Pick the table
social_postsand the events Insert and Update. - Choose Supabase Edge Functions as the type and select
fuxux-send. - Add an HTTP header named
x-webhook-secretwith yourDB_WEBHOOK_SECRETvalue.
5. Try it
-- No date: becomes a draft in Fuxux
insert into public.social_posts (captions)
values ('{"linkedin": "Version 2 is out."}');
-- With a date: scheduled in Fuxux
insert into public.social_posts (captions, scheduled_at)
values ('{"bluesky": "Version 2 is out."}', now() + interval '1 day');
select id, status, fuxux_post_id, error from public.social_posts;The rows should move to draft and scheduled, and the posts appear in your Fuxux calendar. Platform ids and caption rules are in the API reference.
Status values
| Status | Meaning |
|---|---|
queued | Waiting to be sent to Fuxux. |
sending | The function is creating the post. |
draft | Saved as a draft in Fuxux. |
scheduled | Scheduled in Fuxux. |
published | Published on every network. |
partially_failed | Published on some networks. See failed_platforms and error. |
failed | Failed on every network. See error. |
error | Fuxux didn't accept the post. See error. |
To try a row again after error, or one left in sending, set its status back to queued. The row id is sent as an idempotency key, so a repeat within 24 hours can't create a second post. Creating posts is limited to 30 per 5 minutes.