Files
WRNexusJS/examples/basic-app/app/middleware/auth.ts
T
2026-07-12 15:55:18 +05:30

17 lines
730 B
TypeScript

import { getUser, type Context, type Next } from "@wrnexus/core";
// Hydrates ctx.user from the session on every request, then guards protected
// routes. `getUser(ctx)` is then available to every downstream page/API route.
export default async function auth(ctx: Context, next: Next) {
// Populate ctx.user from the session (equivalent to the sessionAuth() helper).
ctx.user = ctx.session.get("user") ?? null;
// Protect the dashboard: send anonymous visitors to the login page.
if (ctx.url.pathname.startsWith("/dashboard") && getUser(ctx) == null) {
return new Response(null, { status: 302, headers: { Location: "/login?next=/dashboard" } });
}
ctx.locals.requestId = crypto.randomUUID();
return next();
}