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

  1. On every request, middleware reads the access token from cookies
  2. Validates the JWT against your project's JWKS endpoint (keys are cached)
  3. If valid → request proceeds
  4. If expired but refresh token exists → attempts silent refresh
  5. 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

OptionTypeDefaultDescription
projectIdstringrequiredProject UUID for JWKS lookup
publicRoutesstring[]["/"]Routes that skip authentication
signInUrlstring"/login"Redirect for unauthenticated users
cookiePrefixstring"vibeauth"Cookie name prefix
apiUrlstring"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.