Express Middleware
auth.middleware.express()
Validates the Authorization: Bearer <token> header (or the auth cookie, if
cookie mode is enabled), populates req.user and
req.session, and calls session.touch() on each request. Responds 401 with
a JSON body when the token is missing, invalid, or the session was revoked.
app.get("/profile", auth.middleware.express(), (req, res) => {
res.json(req.user);
});When resolveUser is configured, req.user is the full resolved User;
otherwise it’s the decoded TokenPayload.
auth.middleware.role(roles)
Role-based access control. Must be placed after express() - it relies on
req.user being set first. Responds 403 if the user’s role isn’t in the
allowed list. Users without a role default to "user".
app.delete(
"/admin/users/:id",
auth.middleware.express(),
auth.middleware.role(["admin", "superadmin"]),
handler,
);role() must always come after express().
httpOnly cookie mode
Pass cookies to createAuth() and the middleware reads tokens from cookies
instead of the Authorization header. Two helpers set and clear them:
const auth = createAuth({
jwt: { secret: process.env.JWT_SECRET! },
cookies: { sameSite: "lax", secure: true }, // names default to guardo_access / guardo_refresh
});const result = await auth.auth.loginWithOtp({ identifier, otp });
// Set httpOnly cookies on the response
auth.middleware.setTokenCookies(res, result.accessToken, result.refreshToken);
res.json({ user: result.user });
// On logout, clear them
auth.middleware.clearTokenCookies(res);CookieOptions:
| Field | Type | Default | Description |
|---|---|---|---|
accessTokenCookie | string | "guardo_access" | Access-token cookie name. |
refreshTokenCookie | string | "guardo_refresh" | Refresh-token cookie name. |
domain | string? | - | Cookie domain. |
path | string | "/" | Cookie path. |
sameSite | "strict" | "lax" | "none" | "lax" | SameSite attribute. |
secure | boolean | true | Secure flag - keep true in production. |
Cookies are always set httpOnly.