Protect a Fastify API using MonoCloud access token validation.
In this quickstart, you will:
Before you begin, make sure you have:
dotenv for loading environment variablesA complete working example is available at: https://github.com/monocloud/fastify-backend-quickstart
https://api.example.com) — this uniquely identifies your APIexample-api and mark the scope as a default scopeKeep this tab open. You'll need the Tenant Domain and Audience next.
Install the SDK:
npm install @monocloud/backend-node
Create a .env file in your project root:
MONOCLOUD_BACKEND_TENANT_DOMAIN=https://<your-domain>
MONOCLOUD_BACKEND_AUDIENCE=https://<your-api-audience>
Create src/server.ts:
import "dotenv/config";
import Fastify from "fastify";
import {
protectApi,
type AuthenticatedFastifyRequest,
} from "@monocloud/backend-node/fastify";
const app = Fastify();
const protect = protectApi();
app.addHook("onRequest", protect());
app.get("/api/protected", async (request) => {
const { claims } = request as AuthenticatedFastifyRequest;
return {
message: "Protected endpoint",
claims,
};
});
app.listen({ port: 3000 }, (err, address) => {
if (err) throw err;
console.log(`Server running on ${address}`);
});
The protect() middleware:
app.addHook("onRequest", protect())request.claimsStart the server:
npx tsx src/server.ts
Your API will be available at: http://localhost:3000
The /api/protected route requires a valid access token.
curl -H "Authorization: Bearer <your-access-token>" http://localhost:3000/api/protected