CodShot
TypeScript Public

Next.js Proxy Authentication Guard

Redirect unauthenticated requests from protected routes with the Next.js proxy convention.

#nextjs #proxy #auth #security
TypeScript
// proxy.ts

import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';

export function proxy(request: NextRequest) {
  const sessionId = request.cookies.get('session')?.value;

  if (!sessionId) {
    const signInUrl = new URL('/signin', request.url);

    signInUrl.searchParams.set(
      'next',
      request.nextUrl.pathname,
    );

    return NextResponse.redirect(signInUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    '/dashboard/:path*',
    '/settings/:path*',
  ],
};

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support