Middleware is where LessJS connects route-tree structure with production safety: request headers, CSP, auth guards, CORS and API-specific protections.
LessJS middleware is Hono middleware mounted from file-system route scopes. A middleware file affects its route subtree; nested middleware composes from outer to inner scope.
| File | Intended scope |
|---|---|
| app/routes/_middleware.ts | All pages and API routes. |
| app/routes/admin/_middleware.ts | /admin/* |
| app/routes/api/_middleware.ts | /api/* |
// app/routes/admin/_middleware.ts
import type { Context, Next } from 'hono';
export default async function adminOnly(c: Context, next: Next) {
const session = c.req.header('x-session');
if (!session) return c.text('Unauthorized', 401);
await next();
}
CSP is a framework-level trust boundary because LessJS emits HTML, DSD templates and island scripts. If CSP is enabled for SSR responses, SSG output must receive the equivalent meta policy during static post-processing.
// vite.config.ts
less({
middleware: {
csp: {
policy: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'",
nonce: false,
reportOnly: false,
},
},
});
Configure CORS deliberately for API routes. Content pages often do not need cross-origin access; API routes often do.
less({
middleware: {
corsOrigin: 'https://example.com',
},
});
Common production headers should be enabled in one place and tested through both SSR and SSG paths.
Two security issues should stay visible until fixed: root middleware must mount across the whole route tree, and SSG must not drop CSP when it post-processes static HTML. These are P1 reliability items because they affect production protections, not only developer ergonomics.