Using Nodora in middleware
Evaluate rules in Next.js, Express, or Hono middleware
Middleware is a natural home for rules that decide whether a request should go through: access checks, feature gating, plan limits, regional restrictions. You evaluate a rule on the way into a route, then either reject the request or attach the result for the handler to use.
The evaluator runs in-process, so a rule evaluated in middleware adds no network hop to the request.
The pattern
The shape is the same in every framework:
- Load the compiled ruleset and create the evaluator once, when the module loads.
- Write a small middleware factory that takes a rule name.
- In the middleware, build the rule input from the request, evaluate, and act on the outputs.
The examples below gate a /beta route with a CanAccessBeta rule that
returns an allowed output:
// middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { createEvaluator } from "@nodora/js";
import ruleset from "@/rules/access.json";
const evaluatorPromise = createEvaluator(ruleset);
export async function middleware(req: NextRequest) {
const evaluator = await evaluatorPromise;
const { userId } = await auth();
const result = await evaluator.evaluateAsync("CanAccessBeta", {
userId,
path: req.nextUrl.pathname,
});
if (!result.outputs.allowed) {
const url = req.nextUrl.clone();
url.pathname = "/";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = { matcher: "/beta/:path*" };auth() is a stand-in for whatever you use to resolve the current
user (NextAuth, Clerk, your own session helper). Next.js middleware
runs on the Edge runtime by default. If you run into WASM limits
there, switch to Node.js by adding runtime: "nodejs" to config.
import express, { NextFunction, Request, Response } from "express";
import { readFile } from "node:fs/promises";
import { createEvaluator } from "@nodora/js";
const ruleset = await readFile("./rules/access.json", "utf8");
const evaluator = await createEvaluator(ruleset);
function requireRule(rule: string) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
const { userId } = await auth(req);
const result = await evaluator.evaluateAsync(rule, {
userId,
path: req.path,
});
if (!result.outputs.allowed) {
return res.sendStatus(403);
}
res.locals.ruleResult = result;
next();
} catch (err) {
next(err);
}
};
}
const app = express();
app.get("/beta/dashboard", requireRule("CanAccessBeta"), (req, res) => {
res.json({ hello: "beta" });
});auth(req) is a stand-in for whatever session or JWT helper your
app already uses to identify the caller. Errors are passed to
next(err) so they go through Express's normal error handling.
import { Hono } from "hono";
import { createMiddleware } from "hono/factory";
import { createEvaluator } from "@nodora/js";
import ruleset from "./rules/access.json";
const evaluator = await createEvaluator(ruleset);
const requireRule = (rule: string) =>
createMiddleware(async (c, next) => {
const { userId } = await auth(c);
const result = await evaluator.evaluateAsync(rule, {
userId,
path: c.req.path,
});
if (!result.outputs.allowed) {
return c.body(null, 403);
}
c.set("ruleResult", result);
await next();
});
const app = new Hono();
app.get("/beta/dashboard", requireRule("CanAccessBeta"), (c) =>
c.json({ hello: "beta" }),
);
export default app;auth(c) is a stand-in for whatever resolves the current user from
the Hono context (an earlier middleware, a JWT helper, etc.). On
Workers and other edge runtimes, importing the ruleset as a JSON
module bundles it with the worker, so nothing is read from disk at
runtime.
Loading rules dynamically
The examples above load the access ruleset from a file that ships
with the application. If you
roll rules out dynamically
instead, the middleware itself doesn't change. Only the evaluator does:
rather than creating it once at startup, keep it in a module that
refreshes it in the background when a new version of access is
published, and have the middleware use whichever evaluator is current.
Requests still evaluate against the ruleset already in memory and never
wait on a fetch.
Notes
- Create the evaluator once. Creating it per request adds latency,
and the first
createEvaluatorcall also boots the WebAssembly module. - Handle evaluation errors. Route a failed
evaluateAsynccall through your framework's error path, and decide whether a failure should allow or deny the request. For access checks, denying is usually the safer default. - Keep inputs small. Pass the rule only what it needs from the request (user, path, headers) rather than the whole request object.
- Not everything belongs in middleware. Rules that need data loaded inside the handler, or that compute values rather than allow or block a request, are usually better evaluated in the route handler or service layer. The evaluator call is the same wherever you put it.