Skip to main content

Protect a Node.js API

This quickstart uses the official @guardhouse/node middleware. It validates JWT signatures and checks issuer, audience, and lifetime before the request reaches the route.

1. Register the API Resource

Create an API resource in Guardhouse and give it a stable audience, such as orders_api. Allow the calling client to request that resource and its scopes.

2. Install the Packages

The Node SDK requires Node.js 18 or later.

npm install @guardhouse/node express

3. Add the Middleware

server.mjs
import express from "express";
import { guardhouseMiddleware } from "@guardhouse/node";

const authority = process.env.GUARDHOUSE_AUTHORITY;
const audience = process.env.GUARDHOUSE_AUDIENCE;

if (!authority || !audience) {
throw new Error("GUARDHOUSE_AUTHORITY and GUARDHOUSE_AUDIENCE are required");
}

const app = express();

app.get("/api/public", (_request, response) => {
response.json({ message: "Public" });
});

app.use(
"/api/orders",
guardhouseMiddleware({
authority,
audience,
}),
);

app.get("/api/orders", (request, response) => {
response.json({ subject: request.user?.sub, orders: [] });
});

app.listen(3000, () => console.log("API listening on http://localhost:3000"));

Run it with values from the Guardhouse dashboard:

GUARDHOUSE_AUTHORITY="https://your-tenant.guardhouse.cloud" \
GUARDHOUSE_AUDIENCE="orders_api" \
node server.mjs

On Windows PowerShell, set the equivalent environment variables for the process before running node server.mjs.

4. Call the Endpoint

curl "http://localhost:3000/api/orders" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

The middleware returns an authentication error when the bearer token is missing or invalid. A valid token issued for another audience is not accepted.

5. Require a Scope

For a route whose token must contain a particular API scope, configure the middleware with the registered scope name:

guardhouseMiddleware({
authority,
audience,
requiredScopes: ["orders.read"],
});

Replace orders.read with a scope registered for your API. For introspection mode and additional validation controls, see Protect an API.