Skip to content

Carry app data through a social sign-in

For: an app developer who must know what the person chose before a social sign-in, such as a plan or an invitation code.

What it does: the social start takes a JSON object in data. Core seals it in the state row, and the callback gives it to your hooks as stateData.

  1. Set social.stateData in the config. maxBytes is 1 to 1024, and the default is 1024.
  2. Read stateData in hooks.session.afterCreate. A link gives it to hooks.identity.afterLink, with via: "link".
The payload in the config and in the hook
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** The plan that each new sign-in asked for. A real app writes its own table. */
export const chosenPlans: string[] = [];
export function createStateDataAuth(deps: {
storage: StorageAdapter;
mail: MailPort;
secret: string;
}) {
return createAuth({
baseURL: "https://api.example.com",
appURL: "https://app.example.com",
trustedOrigins: ["https://app.example.com"],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
social: {
google: { clientId: "google-client-id", clientSecret: "google-client-secret" },
// The start takes `data`: at most 512 bytes of JSON here, sealed in the state row.
stateData: { maxBytes: 512 },
},
hooks: {
session: {
// The browser sent the payload: read it as a wish, never as a right.
async afterCreate({ user, stateData }) {
if (typeof stateData?.plan === "string") chosenPlans.push(`${user.id} ${stateData.plan}`);
},
},
},
});
}
/** The start URL with the payload: the base64url of its UTF-8 JSON. */
export function startUrl(next: string, payload: Record<string, unknown>): string {
let binary = "";
for (const byte of new TextEncoder().encode(JSON.stringify(payload)))
binary += String.fromCharCode(byte);
const data = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
return `/auth/social/google/start?${new URLSearchParams({ next, data })}`;
}
  1. Encode the object as UTF-8 JSON, then as base64url with no padding.
  2. Put it in data on the start URL, beside next. The link start takes data in its body.
The start with a payload as a test
import { describe, expect, it } from "vitest";
import { call, harness } from "../support/harness.ts";
import { createStateDataAuth, startUrl } from "./social-state-data.ts";
describe("carry app data through a social sign-in", () => {
it("starts the flow with the payload and keeps it out of the provider URL", async () => {
const auth = createStateDataAuth(harness());
const res = await call(auth, "GET", startUrl("/welcome", { plan: "pro" }));
expect(res.status).toBe(302);
const to = new URL(res.headers.get("location") ?? "");
expect(to.origin).toBe("https://accounts.google.com");
expect(to.searchParams.has("data")).toBe(false);
});
it("refuses a payload over the bound and a list", async () => {
const auth = createStateDataAuth(harness());
for (const path of [
startUrl("/welcome", { note: "x".repeat(600) }),
"/auth/social/google/start?data=WzFd",
]) {
const res = await call(auth, "GET", path);
expect(new URL(res.headers.get("location") ?? "").searchParams.get("auth_error")).toBe(
"invalid_body",
);
}
});
});
  • The person’s browser sends the payload, so it is never a secret and never a trust decision. Check each value against your own rules.
  • The value must be an object, not a list, with a depth of 4 at most. The depth of the object itself is 1.
  • The state row holds the payload sealed with AES-256-GCM under the current secret version. The row id binds it, so a payload moved to another row does not open.
  • The payload goes to the two hooks only. No redirect, no answer, and no log line holds it.
  • A user with the second factor on gets a challenge at the callback. The challenge row holds the payload sealed, and session.afterCreate gets it at the challenge verify. identity.afterLink gets it at the callback when the sign-in links a new provider account.
  • A state lives 10 minutes. After you make a new secret version current, keep the old version in secrets for 10 minutes at least. Else a flow in progress fails with invalid_token.
  • The Better Auth shim refuses additionalData with NOT_SUPPORTED, because it serves no getOAuthState(). Use core’s createAuth for the payload.
  • invalid_body: social.stateData is off, or data is not base64url JSON. It also answers for a list, more than maxBytes bytes, or a depth over 4. Core writes no state row.
  • invalid_token: the payload did not open at the callback or at the challenge verify. Its secret version left the config, or the row changed. Start again.