How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
Connecting someone's Facebook Page or YouTube channel so a worker can post on a schedule means holding tokens you didn't issue. Each platform has its own rules for keeping them alive, and some quietly stop accepting them. The project is a post scheduler, a pnpm monorepo with a NestJS API, a worker and Postgres through Prisma. Refresh tokens for your own app's login are covered in refresh tokens in a Next.js App Router project.
Complete the OAuth callback from a signed-in session
The authorization-code flow (RFC 6749, section 4.1) has two legs: send the browser to the consent screen with a state, then exchange the returned code. On the first leg the API writes a pending row before building the URL:
// channels.service.ts, startOAuth (trimmed)
const state = crypto.randomToken(24); // 24 random bytes, base64url
const codeVerifier = createCodeVerifier(); // RFC 7636
await prisma.oAuthState.create({
data: {
state,
workspaceId,
userId,
platform,
codeVerifier,
expiresAt: new Date(Date.now() + 10 * 60 * 1000),
},
});
return { url: adapter.buildAuthUrl({ state, codeVerifier }) };
// pkce.ts
export const createCodeVerifier = () => randomBytes(32).toString('base64url'); // 43 chars
export const codeChallengeS256 = (verifier: string) =>
createHash('sha256').update(verifier).digest('base64url');
Ten minutes is RFC 6749's recommended maximum for a code. PKCE came with the X adapter, since X requires code_challenge and RFC 9700 recommends PKCE for confidential clients too. A verifier is created for each connect, and the platform's adapter sends the challenge only where the platform accepts it.
The callback route is public, because the browser returns from Facebook without my auth header. state proves the response belongs to my request, not that this browser started it, since a link can be forwarded (RFC 6749 section 10.12). So the callback exchanges nothing. The code is encrypted and parked on the row, and the browser gets a one-time completion token that the web app posts from a signed-in session:
// handleOAuthCallback: public, so it only parks the code
const completion = crypto.randomToken(24);
const parked = await prisma.oAuthState.updateMany({
where: { id: stored.id, completionHash: null },
data: { codeCiphertext: crypto.encrypt(code), completionHash: crypto.hashToken(completion) },
});
if (parked.count !== 1) return redirectWithError('This connection link expired, try again');
return redirectTo({ complete: completion });
// completeOAuth: POST /oauth/complete, signed in
const stored = await prisma.oAuthState.findUnique({
where: { completionHash: crypto.hashToken(token) },
});
if (!stored?.codeCiphertext) return expired();
// Claim it first, so two tabs can't both exchange the same code.
const claimed = await prisma.oAuthState.deleteMany({
where: { id: stored.id, completionHash: stored.completionHash },
});
if (claimed.count !== 1 || stored.expiresAt.getTime() <= Date.now()) return expired();
if (stored.userId !== userId) throw new ForbiddenException('Started by another account');
// ...still OWNER or ADMIN of that workspace? Only then exchange the code.
A mismatched user burns the row. The worst case is one more click on "Connect". Storing the platform on the row also fixed a bug. Facebook and Instagram share the redirect URI /oauth/facebook/callback, and taking the platform from the path made every Instagram connect store a Facebook Page. The platform now comes from the row.
Encrypt the tokens, and store what you were given
Every token goes into Postgres encrypted with AES-256-GCM, including the parked code:
// crypto.service.ts
encrypt(plaintext: string): string {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', this.key, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return ['v1', Buffer.concat([iv, tag, ciphertext]).toString('base64url')].join(':');
}
Each call gets a fresh IV, the auth tag is stored with the ciphertext, and a version prefix leaves room for a new format. The key comes from the environment, never from the database it protects. The completion token is only ever compared, so it's hashed instead.
A refresh token has three states: undefined (not mentioned), null (none) and a value. Google's refresh response has no refresh_token, so writing refreshed.refreshToken ?? null wipes a good token and the channel breaks an hour later. My persist step only touches that column when the field is present.
Meta lets people untick permissions. The connect reads /me/permissions afterwards and refuses right away if a publishing permission is missing.
One refresh service for every caller
At first only the publisher refreshed, so the metrics sync used stale tokens and got 401s overnight while the channel still read "connected". Now the publisher, metrics sweep and composer share one service:
export const REFRESH_MARGIN_MS = 60_000;
export function needsRefresh(expiresAt: number | null, now: number, marginMs = REFRESH_MARGIN_MS) {
if (expiresAt === null) return false; // "never told us" is not "expired"
return expiresAt < now + marginMs;
}
async ensureFreshToken(channel: Channel, marginMs = REFRESH_MARGIN_MS) {
const current = toAdapterChannel(channel, this.crypto); // decrypts both tokens
const expiresAt = channel.tokenExpiresAt?.getTime() ?? null;
if (!needsRefresh(expiresAt, Date.now(), marginMs)) return current;
const adapter = this.registry.get(current.platform);
if (!adapter.refresh) return current;
const refreshed = await adapter.refresh(current);
if (!refreshed) {
throw new PlatformError(`${current.name} needs to be reconnected`, {
retryable: false,
credentialProblem: true,
});
}
await this.persist(channel, refreshed);
return { ...current, ...pickTokens(refreshed) };
}
A null expiry means the provider never reported one (Meta Page tokens). Treating it as expired calls refresh on every request. The margin exists because a large video upload can take minutes.
A sweep runs every ten minutes (a pg-boss cron plus a process-local timer) and rotates anything expiring within fifteen. The margin must exceed the interval, and a unit test pins that. The sweep takes a Postgres advisory lock because TikTok may return a new refresh_token (RFC 6749 section 6 says to drop the old one), and two processes refreshing at once would flag a healthy channel.
Six platforms, six sets of token rules
Google issues a refresh token only on the first authorization with access_type=offline. It stops working after six months unused, past 100 per account and client, or after seven days for an external app in Testing.
Meta exchanges a short-lived user token for a roughly 60-day one (fb_exchange_token), and Page tokens fetched with it don't expire, so Facebook channels don't store an expiry. Threads extends the access token itself with th_refresh_token. TikTok gives 24-hour access and 365-day refresh tokens. LinkedIn reserves refresh tokens for approved partners, so users reconnect every 60 days. X issues one only with offline.access.
So refresh() is optional on the adapter interface, and the health check asks "can this adapter refresh?" instead of "is refreshToken null?".
Only credential failures flag the channel
Every failure raises two separate questions, whether to retry and whether reconnecting would fix it. My first version marked NEEDS_REAUTH on any permanent failure, including an Instagram error caused by a media URL on localhost. Now only credential failures touch the channel, and other errors stay on the post.
// http.ts, inside httpJson on a non-2xx response
throw new PlatformError(describeError(status, body, provider), {
retryable: status === 429 || status >= 500 || isMetaRateLimit(body),
credentialProblem: status === 401 || status === 403 || classifyCredentialBody(body),
});
export function classifyCredentialBody(body: unknown): boolean {
const error = (body as { error?: Record<string, unknown> } | null)?.error;
if (!error || typeof error !== 'object') return false;
const code = Number.parseInt(String(error.code ?? ''), 10);
if (code === 190 || code === 102) return true; // Meta: invalid token or session
// X sends 32/89 for a dead token; Meta's 32 is a Page request limit.
return (code === 32 || code === 89) && !isMetaErrorBody(error);
}
Meta answers an expired token with HTTP 400 and error.code: 190. A 32 from X is a dead token, while from Meta it's a Page request limit, and misreading it blocks every later post on that Page.
The sweep used to flag a channel only once its token had expired, so when a provider answered invalid_grant with 14 minutes left, nobody knew until a scheduled post failed nine hours later. Now a refusal is flagged immediately and a timeout on a live token is ignored. Adapters also rethrow a 5xx during refresh instead of returning null.
A flagged channel gets an activity log entry with the failure type, its posts fail with the channel name and the fix, and a notice goes out once per post by email and in the app. A later successful refresh or publish moves it back to CONNECTED.
Testing the rules as pure functions
The tests use node:test through tsx, and most rules are pure functions that take now, with no clock or database:
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
const NOW = 1_800_000_000_000;
describe('token refresh window', () => {
it('does not refresh a token whose expiry the provider never reported', () => {
assert.equal(needsRefresh(null, NOW), false);
});
it('refreshes a token that expires inside the margin', () => {
assert.equal(needsRefresh(NOW + REFRESH_MARGIN_MS - 1, NOW), true);
});
});
it('derives the RFC 7636 appendix B challenge from its verifier', () => {
assert.equal(
codeChallengeS256('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'),
'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
);
});
Provider behavior is only covered by a mock adapter that fails on request and a few connects on test accounts. A mock reproduces a quirk like Meta's 32 only once you know it exists.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.
- 03
PageSpeed gave my site 25 on mobile. My own Lighthouse said 90+
My own Lighthouse gave vennee.dev 90+. PageSpeed mobile said 25. A loader hid the LCP, Lighthouse simulated a slow network, and WebGL ran on the CPU.