HyperSaaS
FrontendRouting

Middleware

Authentication middleware for route protection.

The middleware runs on every matching request before the page renders, enforcing authentication on protected routes.

Configuration

// src/middleware.ts
import { auth } from "@/lib/auth/providers";

export default auth;

HyperSaaS uses NextAuth's built-in middleware which automatically verifies the JWT session on protected routes.

Protected Routes

The middleware matcher specifies which routes require authentication:

export const config = {
  matcher: [
    "/pricing",
    "/dashboard/:path*",
    "/api/workspaces/:path*",
    "/api/chats/:path*",
    "/api/invitations/:path*",
    "/api/subscriptions/:path*",
    "/api/transcribe-audio",
  ],
};

Route Protection Behavior

Route PatternBehavior
/dashboard/*Redirect to /login if unauthenticated
/api/workspaces/*Return 401 if no valid JWT
/api/chats/*Return 401 if no valid JWT
/api/subscriptions/*Return 401 if no valid JWT
/pricingRedirect to /login if unauthenticated
/login, /registerAlways accessible (not in matcher)
/, /features, /blog/*Always accessible (not in matcher)

How It Works

  1. Request hits a matched route
  2. NextAuth middleware checks for a valid session cookie
  3. If valid: request proceeds to the page/API handler
  4. If invalid: redirects to /login (pages) or returns 401 (API routes)

Additional Auth Checks

Beyond middleware, individual pages perform their own auth checks for defense in depth:

// Server component pattern
export default async function ProtectedPage() {
  const user = await getCurrentUserServer();
  if (!user) redirect("/login");

  // Page content...
}

API route handlers also validate the JWT token:

// API route pattern
export async function GET() {
  const token = await getAccessToken();
  if (!token) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
  // ...
}

This layered approach ensures protection even if middleware is bypassed or misconfigured.

On this page