Cloudflare Workers

This is how your API handler would typically look like:

src/worker.ts
import { bootstrapAuth, getUser } from "./auth"; // See below

type Env = {
    OIDC_ISSUER_URI: string;
    OIDC_AUDIENCE?: string;
};

let isBootstrapped = false;

function ensureBootstrapped(env: Env) {
    if (isBootstrapped) {
        return;
    }

    bootstrapAuth({
        implementation: "real", // or "mock", see: https://docs.oidc-spa.dev/v/v8/integration-guides/backend-token-validation/mock-modes
        issuerUri: env.OIDC_ISSUER_URI,
        expectedAudience: env.OIDC_AUDIENCE ?? undefined
    });

    isBootstrapped = true;
}

export default {
    async fetch(request: Request, env: Env): Promise<Response> {
        ensureBootstrapped(env);

        const url = new URL(request.url);

        if (request.method === "GET" && url.pathname === "/api/todos") {

            const user = await getUser({ req: request });

            // We got a Response, validation failed
            if (user instanceof Response) {
                return user;
            }

            // Replace this with KV / D1 / R2 / your DB call.
            const json = JSON.stringify([
                { id: "1", label: "Write documentation", ownerId: user.id }
            ]);

            return new Response(json, {
                status: 200,
                headers: { "content-type": "application/json" }
            });
        }

        /**
         * Support staff endpoint.
         * Example: GET /api/todos-for-support/1234
         */
        if (
            request.method === "GET" &&
            url.pathname.startsWith("/api/todos-for-support/")
        ) {
            let userId: string;

            try {
                userId = decodeURIComponent(
                    url.pathname.replace("/api/todos-for-support/", "")
                );
            } catch {
                return new Response("bad request", { status: 400 });
            }

            if (!userId || userId.includes("/")) {
                return new Response("bad request", { status: 400 });
            }

            {
                // Will reject the request if user making the request
                // doesn't have "support-staff" role
                const user = await getUser({
                    req: request,
                    requiredRole: "support-staff"
                });

                if (user instanceof Response) {
                    return user;
                }
            }

            // Replace this with KV / D1 / R2 / your DB call.
            const json = JSON.stringify([
                { id: "1", label: "Support view", ownerId: userId }
            ]);

            return new Response(json, {
                status: 200,
                headers: { "content-type": "application/json" }
            });
        }

        return new Response("not found", { status: 404 });
    }
};

Auth utilities

Let’s see how to export the utils to make it happen:

Last updated

Was this helpful?