Core Concepts
Middleware
Middleware handles cross-cutting HTTP concerns before the controller runs.
Use middleware for things that apply to many routes: authentication, throttling, authorization, sessions, CORS, or request shaping.
The Mental Model
The request flow is:
Request -> Middleware -> Controller -> Response
Each middleware should do one small job, then call next().
Quick Example
import { Router } from "@admicaa/netpress";
import authMiddleware from "../app/Http/Middleware/auth.js";
import throttle from "../app/Http/Middleware/throttle.js";
import AuthController from "../app/Http/Controllers/Auth/AuthController.js";
import UserController from "../app/Http/Controllers/UserController.js";
const router = Router();
router.group(throttle(30, 60), (router) => {
router.post("/login", AuthController.login);
});
router.group(authMiddleware, (router) => {
router.get("/me", UserController.me);
});
Common Starter Middleware
The starter includes middleware for common app needs:
auth.jsauthenticates the request through the core guard managerrole.jsadds simple role checks and policy middleware helpersthrottle.jsrate-limits repeated requestscors.jsconfigures cross-origin accesssession.js,csrf.js, andshareViewState.jssupport server-rendered flowserrorHandler.jsnormalizes thrown errors
The core also ships cookie security middleware for Laravel-style browser flows:
createEncryptCookiesMiddleware()encrypts cookies withAPP_KEYcreateCsrfProtectionMiddleware()validates_tokenandX-XSRF-TOKEN
The starter keeps them on the web side only:
routes/web.jsmounts encrypted cookies, the lazy session, shared view state, and CSRFroutes/api.jsdoes not mount cookie, session, or CSRF middleware
Authorization Middleware
Simple role check:
import { requireRole } from "../app/Http/Middleware/role.js";
router.group(authMiddleware, (router) => {
router.group(requireRole("admin"), (router) => {
router.get("/users", UserController.index);
});
});
Policy middleware:
import { authorize } from "../app/Http/Middleware/role.js";
import UserPolicy from "../app/Policies/UserPolicy.js";
router.delete(
"/users/:id",
authMiddleware,
authorize(UserPolicy, "delete", (req) => UserService.findById(req.params.id)),
UserController.destroy,
);
If you want Laravel-style roles, permissions, and route guards, use the companion package: NetPress Permissions.
Custom Middleware
Custom middleware should stay small and focused:
import { HttpException } from "@admicaa/netpress";
export default function ensureInternalRequest(req, _res, next) {
if (req.headers["x-internal-token"] !== process.env.INTERNAL_TOKEN) {
throw new HttpException(403, "Forbidden");
}
next();
}
Good Middleware Rules
- keep business logic out of middleware
- keep middleware composable and single-purpose
- prefer route groups when many routes share the same middleware
- throw exceptions and let the global handler format the response
Next, read Authentication and Authorization.