Sign in

Fastify Backend Quickstart

Protect a Fastify API using MonoCloud access token validation.

In this quickstart, you will:

  • Create an API resource on MonoCloud
  • Install the MonoCloud Backend Node SDK
  • Protect Fastify routes with Bearer token validation
  • Read claims from the authenticated token

Prerequisites

Before you begin, make sure you have:

  • A MonoCloud account and tenant
  • Node.js 18+ (npm, Yarn, or PNPM)
  • An existing Fastify project
  • dotenv for loading environment variables
A complete working example is available at: https://github.com/monocloud/fastify-backend-quickstart

Configure MonoCloud

  1. In the MonoCloud Dashboard, create a new API
  2. Set the Audience (for example https://api.example.com) — this uniquely identifies your API
  3. Add a scope named example-api and mark the scope as a default scope
Keep this tab open. You'll need the Tenant Domain and Audience next.

Install the SDK

Install the SDK:

Terminal
npm install @monocloud/backend-node

Configure environment variables

Create a .env file in your project root:

.env
MONOCLOUD_BACKEND_TENANT_DOMAIN=https://<your-domain>
MONOCLOUD_BACKEND_AUDIENCE=https://<your-api-audience>

Protect your API

Create src/server.ts:

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}`);
});

How it works

The protect() middleware:

  • Protects all routes registered after app.addHook("onRequest", protect())
  • Validates the incoming Bearer token
  • Verifies issuer, audience, and signature
  • Returns 401 Unauthorized if invalid
  • Attaches validated claims to request.claims

Run the application

Start the server:

Terminal
npx tsx src/server.ts

Your API will be available at: http://localhost:3000

Test the protected route

The /api/protected route requires a valid access token.

Terminal
curl -H "Authorization: Bearer <your-access-token>" http://localhost:3000/api/protected
© 2024 MonoCloud. All rights reserved.