Sign in

Express Backend Quickstart

Protect an Express API using MonoCloud access token validation.

In this quickstart, you will:

  • Create an API resource on MonoCloud
  • Install the MonoCloud Backend Node SDK
  • Protect Express 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 Express project
  • dotenv for loading environment variables
A complete working example is available at: https://github.com/monocloud/express-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 express from "express";
import {
  protectApi,
  type AuthenticatedExpressRequest,
} from "@monocloud/backend-node/express";

const app = express();
const protect = protectApi();

app.use(express.json());
app.use(protect());

app.get("/api/protected", (req, res) => {
  const { claims } = req as AuthenticatedExpressRequest;

  res.json({
    message: "Protected endpoint",
    claims,
  });
});

app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});

How it works

The protect() middleware:

  • Protects all routes registered after app.use(protect())
  • Validates the incoming Bearer token
  • Verifies issuer, audience, and signature
  • Returns 401 Unauthorized if invalid
  • Attaches validated claims to req.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.