C.W.K.
Stream
Lesson 03 of 09 · published

Proxy Use Cases

~20 min · auth gate, geo, A/B testing

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Auth gate

Read the session cookie. Redirect signed-out users away from protected paths and signed-in users away from /login.

Geolocation routing

Vercel exposes request.geo with country / region / city. Redirect to a locale-specific path on first hit.

A/B test bucketing

Set a cookie on first visit picking a variant. Subsequent requests read the cookie and route accordingly. The bucket survives navigation without server state.

Header rewriting

Add security headers, request IDs, or feature-flag headers that downstream code can read.

Code

Auth gate·ts
import { NextRequest, NextResponse } from 'next/server';

export function proxy(request: NextRequest) {
  const session = request.cookies.get('session');
  const isAuth = request.nextUrl.pathname.startsWith('/login');
  const isProtected = request.nextUrl.pathname.startsWith('/app');

  if (isProtected && !session) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  if (isAuth && session) {
    return NextResponse.redirect(new URL('/app', request.url));
  }
  return NextResponse.next();
}
Geo redirect·ts
export function proxy(request: NextRequest) {
  const country = request.geo?.country ?? 'US';
  if (country === 'KR' && !request.nextUrl.pathname.startsWith('/ko')) {
    return NextResponse.redirect(new URL('/ko' + request.nextUrl.pathname, request.url));
  }
  return NextResponse.next();
}
A/B bucket·ts
export function proxy(request: NextRequest) {
  const bucket = request.cookies.get('ab')?.value;
  const res = NextResponse.next();
  if (!bucket) {
    res.cookies.set('ab', Math.random() < 0.5 ? 'A' : 'B', {
      maxAge: 60 * 60 * 24 * 30,
      httpOnly: true,
    });
  }
  return res;
}

External links

Exercise

Add three behaviors to your proxy.ts: an auth gate, a security header injection (e.g. CSP), and an A/B cookie. Verify each via curl.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.