Skip to content

Your first sign-in from a web app

For: a web developer who has an API with authtempo and a browser app on another origin.

What it does: the browser app asks for a magic link, shows the signed-in address, and signs the person out.

An agent can do these steps with the authtempo MCP server. See Set up an agent.

  • An API with authtempo. Do one of the stack tutorials first, such as Workers on D1.
  • A browser app on its own origin. This tutorial uses https://app.example.com for the app and https://api.example.com for the API. Run the app on another origin tells the rules.
  1. On the API, set appURL to the origin of the app, and add the same origin to trustedOrigins.
The API config
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** The API at https://api.example.com, for a browser app at https://app.example.com. */
export function createApiAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string }) {
return createAuth({
baseURL: "https://api.example.com",
// The browser lands here after a sign-in. It must be in trustedOrigins too.
appURL: "https://app.example.com",
// A trusted origin gets credentialed CORS, and its POSTs pass the Origin rule.
trustedOrigins: ["https://app.example.com"],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
});
}
  1. At the root of the repo, add the client package to your app: pnpm --filter <your-app> add "@authtempo/client@workspace:*".
  2. Make one client for the app, and write the three calls of the sign-in.
The browser app
import { type Client, createClient } from "@authtempo/client";
/** The client of the browser app. It sends the session cookie to the API origin. */
export function createAppClient(fetchImpl: typeof fetch = globalThis.fetch): Client {
return createClient({ baseURL: "https://api.example.com", fetch: fetchImpl });
}
/** The sign-in form posts the address. The API mails a link that lands on /welcome. */
export async function askForLink(client: Client, email: string): Promise<string> {
const r = await client.magicLink.request({ email, next: "/welcome" });
return r.ok ? "Check your mail for the sign-in link." : `The request failed: ${r.code}.`;
}
/** The page at /welcome shows the signed-in address. Show it after every sign-in. */
export async function welcome(client: Client): Promise<string> {
const r = await client.session();
if (!r.ok) return `The API did not answer: ${r.code}.`;
return r.value ? `Signed in as ${r.value.user.email}.` : "Not signed in.";
}
/** The sign-out button. The API deletes the session and clears the cookie. */
export async function signOut(client: Client): Promise<boolean> {
return (await client.signOut()).ok;
}
  1. On the sign-in form, call askForLink with the address that the person types.
  2. Open the mail, and open the link. The API shows a confirm page with one button.
  3. Press the button. The browser goes to https://app.example.com/welcome with the session cookie.
  4. On the page at /welcome, call welcome. It shows the signed-in address.
  5. On the sign-out button, call signOut.

The test below runs the same steps against the API in memory. It plays the browser: it keeps the cookie and sends the app’s origin.

The test of this tutorial
import type { Auth } from "@authtempo/core";
import { describe, expect, it } from "vitest";
import { API, APP, harness, linkIn } from "../support/harness.ts";
import { askForLink, createAppClient, signOut, welcome } from "./first-sign-in.ts";
import { createApiAuth } from "./first-sign-in-api.ts";
/** A browser on APP: it sends its Origin, keeps the API's session cookie, and sends it back. */
function browser(auth: Auth): typeof fetch {
let cookie = "";
return (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
const req = new Request(input, init);
const headers = new Headers(req.headers);
headers.set("origin", APP);
if (cookie) headers.set("cookie", cookie);
const body = req.method === "GET" ? null : await req.text();
const res = await auth.handle(new Request(req.url, { method: req.method, headers, body }));
for (const c of res.headers.getSetCookie()) {
const pair = c.split(";")[0] ?? "";
if (pair.startsWith("__Host-tempo_session="))
cookie = pair === "__Host-tempo_session=" ? "" : pair;
}
return res;
}) as typeof fetch;
}
describe("your first sign-in from a web app", () => {
it("signs in by magic link, shows the address, and signs out", async () => {
const h = harness();
const auth = createApiAuth(h);
const b = browser(auth);
const client = createAppClient(b);
expect(await welcome(client)).toBe("Not signed in.");
expect(await askForLink(client, "ada@example.com")).toBe(
"Check your mail for the sign-in link.",
);
// The person opens the link, and the confirm page posts its form.
const link = linkIn(h, "ada@example.com");
expect(`${link.origin}${link.pathname}`).toBe(`${API}/auth/magic-link/verify`);
const press = await b(`${API}/auth/magic-link/verify`, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token: link.searchParams.get("token") ?? "" }).toString(),
redirect: "manual",
});
expect(press.status).toBe(302);
expect(press.headers.get("location")).toBe(`${APP}/welcome`);
expect(await welcome(client)).toBe("Signed in as ada@example.com.");
expect(await signOut(client)).toBe(true);
expect(await welcome(client)).toBe("Not signed in.");
});
});

The page at /welcome shows “Signed in as” and the address. After the sign-out it shows “Not signed in.”.

A client call never throws for an answer. It answers { ok: true, value } or { ok: false, code, status }. Read code when ok is false.