Rewrite Domain in Set-Cookie in Nextjs dev server

201 Views Asked by At

We use CORS + SameSite to prevent CSRF attack on the server side & Next.js build a static site with Apache mod_proxy, the Domain component is handled by Apache's ProxyPassReverseCookieDomain directive.

This CSRF protection breaks local dev-server. Initially we configured rewrites in next.config.js:

if (process.env.BACKEND_API) {
    nextConfig.rewrites = async () => {
        return [
            {
                source: '/api/:path*',
                destination: `${process.env.BACKEND_API}/:path*`
            }
        ]
    }
}

But now we need middleware to rewrite Set-Cookie Domain from one name to the localhost...

Is it possible to define middleware action on cookies only for dev-server?

1

There are 1 best solutions below

0
stonith404 On

Here is a middleware located in src/middleware.ts that modifies the Domain attribute:

export async function middleware(request: NextRequest) {
  // Only run this middleware in development
  if (process.env.NODE_ENV !== "development") return NextResponse.next();

  // GET request to get the original headers
  const { headers } = await fetch(request);

  if (headers.has("Set-Cookie")) {
    const cookies = headers.get("Set-Cookie")!;

    // Replace the Domain attribute to localhost
    const modifiedCookies = cookies.replace(/Domain=[^;]+/, "Domain=localhost");

    // Set the modified Set-Cookie header
    headers.set("Set-Cookie", modifiedCookies);
  }

  return NextResponse.next({
    headers: headers,
  });
}

export const config = {
  matcher: "/api/:path*",
};

This solution, however, presents two disadvantages:

  • It necessitates an additional fetch call to the backend to retrieve the cookies.
  • The response contains two Set-Cookie headers: the original one with the backend domain and another with localhost.