NextJS 16 Proxy issues

Hello,

I have been having issues with my proxy since yesterday. My better-auth session check broke. I was using their better-fetch solution and after I noticed it wasn’t working properly, I moved to their newer nodejs/proxy middleware solution. Here’s my code. My website now doesn’t load at ALL unless i comment out everything in the Proxy.

import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { NextRequest, NextResponse } from "next/server";

const protectedRoutes = ["dashboard", "settings"];

export default async function proxy(req: NextRequest) {
    console.log("PROXY RUNNING");
    const path = req.nextUrl.pathname;

    const segments = path.split("/").filter(Boolean);

    const isProtected = protectedRoutes.some((p) => segments.includes(p));

    if (!isProtected) {
        return NextResponse.next();
    }

    const session = await auth.api.getSession({
        headers: await headers(),
    });

    if (session?.user) {
        console.log(
            `${session.user.name} is accessing protected route: ${path}`,
        );
    } else {
        console.log(`Unauthorized access attempt to: ${path}`);
        return NextResponse.redirect(new URL("/", req.nextUrl));
    }
}

export const config = {
    matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};

Should also mention I am on the Bun runtime.

This has fixed it for me. It still does not make sense why the server-side auth from Better Auth doesn’t work in Vercel but works locally.

import type { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { betterFetch } from "@better-fetch/fetch";
import { type NextRequest, NextResponse } from "next/server";

type Session = typeof auth.$Infer.Session;

export async function proxy(req: NextRequest) {
    const path = req.nextUrl.pathname;

    const { data: session } = await betterFetch<Session>(
        "/api/auth/get-session",
        {
            baseURL: req.nextUrl.origin,
            headers: await headers(),
        },
    );

    if (session?.user) {
        console.log(
            `${session.user.name} is accessing protected route: ${path}`,
        );
    } else {
        console.log(`Unauthorized access attempt to: ${path}`);
        return NextResponse.redirect(new URL("/", req.nextUrl));
    }
}

export const config = {
    matcher: ["/dashboard", "/settings"],
};