Middleware — Route Protection
Overview
VibeLogin's middleware protects your Next.js routes by verifying JWT access tokens on every request. Unauthenticated users are redirected to your sign-in page.
Basic setup
// middleware.ts
import { hostedAuthMiddleware } from "@vibelogin/nextjs/hosted-middleware";
export default hostedAuthMiddleware({
projectId: process.env.VIBELOGIN_PROJECT_ID!,
publicRoutes: ["/", "/pricing", "/about"],
});
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};How it works
- On every request, middleware reads the access token from cookies
- Validates the JWT against your project's JWKS endpoint (keys are cached)
- If valid → request proceeds
- If expired but refresh token exists → attempts silent refresh
- If no valid token → redirects to
signInUrl
Public routes
Routes that don't require authentication. By default, only / is public.
publicRoutes: [
"/", // exact match
"/pricing", // exact match
"/blog/:path*", // wildcard — matches /blog, /blog/post-1, /blog/a/b/c
"/api/public/:path*", // public API routes
]The :path* suffix acts as a wildcard, matching the route and all nested paths beneath it.
Custom sign-in URL
hostedAuthMiddleware({
projectId: process.env.VIBELOGIN_PROJECT_ID!,
publicRoutes: ["/", "/login"],
signInUrl: "/login", // default is "/login"
});Make sure your signInUrl is listed in publicRoutes, otherwise unauthenticated users will hit a redirect loop.
Configuration reference
| Option | Type | Default | Description |
|---|---|---|---|
| projectId | string | required | Project UUID for JWKS lookup |
| publicRoutes | string[] | ["/"] | Routes that skip authentication |
| signInUrl | string | "/login" | Redirect for unauthenticated users |
| cookiePrefix | string | "vibeauth" | Cookie name prefix |
| apiUrl | string | "https://api.vibelogin.com" | API base URL for JWKS + refresh |
Next.js matcher
The matcher config tells Next.js which routes to run middleware on. The recommended pattern excludes static files:
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};How JWT verification works
The middleware fetches your project's public keys from the JWKS endpoint (/v1/jwks/{projectId}) and caches them in memory. Tokens are verified locally using RS256 — no network call to VibeLogin on each request after the initial key fetch.