node:http
This is how your API handler would typically look like:
import { createServer } from "node:http";
import { parse } from "node:url";
import * as fs from "node:fs/promises";
import { bootstrapAuth, getUser } from "./auth"; // See below
function startNodeServer() {
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 server = createServer(async (req, res) => {
const { pathname } = parse(req.url!, true);
if (req.method === "GET" && pathname === "/api/todos") {
const user = await getUser({ req, res });
const json = await fs.readFile(
`todos_${user.id}.json`,
"utf8"
);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(json);
return;
}
if (
req.method === "GET" &&
pathname?.startsWith("/api/todos-for-support/")
) {
// Will reject the request if user making the request
// doesn't have "support-staff" role
await getUser({ req, res, requiredRole: "support-staff" });
const userId = decodeURIComponent(
pathname.replace("/api/todos-for-support/", "")
);
const json = await fs.readFile(
`todos_${userId}.json`,
"utf8"
);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(json);
return;
}
res.writeHead(404).end();
});
server.listen(parseInt(process.env.PORT ?? "3000"), () => {
console.log("Server running");
});
}Let's see how to export the utils to make it happen:
Last updated
Was this helpful?