Fastify

This is how your API handler would typically look like:

src/main.ts
import Fastify from "fastify";
import * as fs from "node:fs/promises";
import { bootstrapAuth, getUser } from "./auth"; // See below

async function startFastifyServer() {

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

    const fastify = Fastify({
        // If you run behind a reverse proxy, you almost always want this enabled.
        // It affects things like the computed request origin.
        trustProxy: true
    });

    fastify.get("/api/todos", async (req, reply) => {

        const user = await getUser({ req, reply });

        const json = await fs.readFile(
            `todos_${user.id}.json`,
            "utf8"
        );

        reply.code(200).type("application/json").send(json);

    });

    fastify.get("/api/todos-for-support/:userId", async (req, reply) => {

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

        const { userId } = req.params as { userId: string };

        const json = await fs.readFile(
            `todos_${userId}.json`,
            "utf8"
        );

        reply.code(200).type("application/json").send(json);

    });

    // ...

    await fastify.listen({
        port: parseInt(process.env.PORT ?? "3000"),
        host: "0.0.0.0"
    });
}

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

Last updated

Was this helpful?