Protect an Express 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/express-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 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");
});
The protect() middleware:
app.use(protect())req.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