如何在 Next.js App Router 中使用 Publora REST API 排程社交媒體貼文並避免洩漏 API key
Schedule social media posts from a Next.js app without leaking your API key
這篇教學示範如何在 Next.js App Router 中使用 Publora REST API 建立或排程社交媒體貼文,並將 API key 僅保留在伺服器端。
Most "post to social media" features I see in Next.js apps start the same way: someone puts an API key in a client component, ships it, and finds it in the browser's network tab a week later.
Here is the setup I recommend instead, using the Publora REST API from the App Router. Everything runs on the server: one small fetch wrapper, one route that creates or schedules a post, and one webhook route that tells you when the post actually went out.
Keep the key on the server
# .env.local: never prefix these with NEXT_PUBLIC_
PUBLORA_API_KEY=sk_YOUR_API_KEY
PUBLORA_BASE_URL=https://api.publora.com/api/v1
PUBLORA_WEBHOOK_SECRET=your_webhook_secret
Anything with NEXT_PUBLIC_ gets bundled into the client. The API key can publish to every account connected to it, so it stays server-only.
A small server-side client
// lib/publora.ts
const baseUrl = process.env.PUBLORA_BASE_URL ?? 'https://api.publora.com/api/v1';
export async function publora<T>(
path: string,
init: RequestInit = {},
idempotencyKey?: string,
): Promise<T> {
const response = await fetch(`${baseUrl}/${path}`, {
...init,
headers: {
'content-type': 'application/json',
'x-publora-key': process.env.PUBLORA_API_KEY!,
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
...init.headers,
},
cache: 'no-store',
});
const body = await response.json();
if (!response.ok) throw new Error(body.error ?? `Publora returned ${response.status}`);
return body as T;
}
Two details matter here. cache: 'no-store' stops Next.js from caching a write. The optional Idempotency-Key header means a retried request (a double click, a flaky network, a serverless retry) replays the first response instead of creating a second post. When a call fails, the error body names the problem; the error code reference lists them all.
The route your UI calls
// app/api/social-posts/route.ts
import { NextResponse } from 'next/server';
import { randomUUID } from 'node:crypto';
import { publora } from '@/lib/publora';
export async function POST(request: Request) {
const { content, platforms, publish } = await request.json();
const scheduledTime = publish
? new Date(Date.now() + 5 * 60_000).toISOString()
: undefined;
const result = await publora<{ success: boolean; postGroupId: string }>(
'create-post',
{
method: 'POST',
body: JSON.stringify({ content, platforms, scheduledTime }),
},
randomUUID(),
);
return NextResponse.json(result);
}
The rule to remember: a post without scheduledTime is a draft. Nothing goes out. So label the buttons honestly, "Create draft" and "Schedule post", and never call a submission without a time "scheduled". If you want it out right away rather than in five minutes, the same endpoint takes publishNow: true instead of a time.
platforms takes the connection IDs from GET /platform-connections (for example linkedin-ABC123). Validate your own user's input before you forward it; this route is the only thing standing between your form and their LinkedIn.
Know when the post went out
Scheduling succeeds long before publishing does. To update your UI when a post is actually live (or failed), add a webhook route:
// app/api/publora-webhook/route.ts
import crypto from 'node:crypto';
export async function POST(request: Request) {
const raw = Buffer.from(await request.arrayBuffer());
const received = request.headers.get('x-publora-signature') ?? '';
const expected = crypto
.createHmac('sha256', process.env.PUBLORA_WEBHOOK_SECRET!)
.update(raw)
.digest('hex');
const valid = received.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
if (!valid) return new Response(null, { status: 401 });
const envelope = JSON.parse(raw.toString('utf8'));
// Enqueue application work here.
return new Response(null, { status: 204 });
}
The signature is an HMAC-SHA256 of the raw request bytes. If you call request.json() first, you verify a re-serialized copy and valid requests start failing. Read the bytes, check the signature, then parse.
I ran this handler against a signed test envelope: the correct signature returns 204, and a wrong signature, a missing one or a modified body all return 401.
Where to go next
The full guide with links to each workflow (drafts, one-shot scheduling, media uploads, updates and webhooks) is in the Next.js integration docs. The complete API surface is in the OpenAPI spec.
Written with Claude.
How do you handle "the post actually went out" in your apps: webhooks, polling, or do you just trust the scheduler?
來源:DEV Community · dev.to