Middleware
Middleware provides server-side route protection. It runs on the Edge before the page renders, preventing unauthenticated users from even reaching protected routes.
TIP
LiteAuthProvider already handles client-side protection automatically. Middleware is optional but recommended for stronger security.
Setup
ts
// middleware.ts
import { middleware } from "@/auth";
export default middleware({
protect: ["/dashboard", "/settings", "/admin"],
});
export const config = {
matcher: ["/((?!_next|api/auth).*)"],
};Options
| Option | Type | Default | Description |
|---|---|---|---|
protect | string[] | — | Route prefixes to protect |
redirectTo | string | "/login" | Where to redirect unauthenticated users |
How it works
- Checks if the current
pathnamestarts with any value inprotect - If not protected — passes the request through
- If protected — reads and verifies the JWT cookie
- Valid token → passes through
- Invalid or missing token → redirects to
redirectTo
Client-side vs server-side protection
LiteAuthProvider | Middleware | |
|---|---|---|
| Where it runs | Browser | Edge (server) |
| How it protects | Renders login UI instead of children | Redirects before page loads |
| Required | Yes | Optional |
| Setup | protect prop | middleware.ts file |
Use both together for the best experience.