Next.js Guide

Next.js Middleware Auth

Protect Next.js routes at the edge with GitHat middleware. Zero-latency auth checks, configurable public routes, and automatic sign-in redirects.

Edge Route Protection

Protect routes at the CDN edge with GitHat middleware. No server-side rendering needed — the middleware intercepts requests and redirects unauthenticated users before the page handler runs.

Configuration

Set up middleware in one file: import authMiddleware, define public routes, and export. The matcher config tells Next.js which paths to check. Exclude _next, api, and static files.

Redirect Flow

The redirect flow preserves user intent: user visits /dashboard, middleware redirects to /sign-in?redirect_url=/dashboard, user signs in, GitHat redirects back to /dashboard.

Install

import { authMiddleware } from '@githat/nextjs/middleware';

Example

// middleware.ts (project root)
import { authMiddleware } from '@githat/nextjs/middleware';

export default authMiddleware({
  publicRoutes: ['/', '/sign-in', '/sign-up', '/pricing', '/forgot-password'],
  signInUrl: '/sign-in',
});

export const config = {
  matcher: ['/((?!_next|api|.*\\..*).*)'],
};
Try GitHat free

Ship authenticated apps in minutes, not weeks.