Categories
Uncategorised

Pass custom headers to `rewrites` proxy

Found a nice and tidy way to add custom headers to the rewrites proxy if you know next.config.js well.

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

export const config = {
  matcher: '/product/:path',
};

// Proxies /product/:id to https://my-proxied-site.com/product/:id
export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('Authorization', 'Bearer ******');

  // Extract product id from pathname
  const [, , id] = request.nextUrl.pathname.split('/');
  request.nextUrl.href = `https://vercel.com/product/${id}`;

  return NextResponse.rewrite(request.nextUrl, {
    request: {
      headers: requestHeaders,
    },
  });
}

A idea from Github: https://github.com/vercel/next.js/discussions/19078