Next.js Discord

Discord Forum

Middleware Redirect Error

Unanswered
Atlantic menhaden posted this in #help-forum
Open in Discord
Atlantic menhadenOP
I have some middleware that triggers a fetch to a route handler that determines whether or not the user is logged in by whether the response has user information. For some reason my middleware in production (behind an NGINX reverse proxy) is triggering this error when trying to redirect the user if they are not logged in to a login page:

failed to get redirect response TypeError: fetch failed
    at node:internal/deps/undici/undici:12502:13
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    ......
  [cause]: AggregateError [ECONNREFUSED]: 
      at internalConnectMultiple (node:net:1117:18)
      at internalConnectMultiple (node:net:1185:5)
      at afterConnectMultiple (node:net:1684:7)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    code: 'ECONNREFUSED',
    [errors]: [ [Error], [Error] ]
  }
}


middleware.ts
import { NextResponse, type NextRequest } from "next/server";
import type { Serialized } from "./lib/util";
import type { SanitizedUser } from "./lib/auth/util";

async function getUser(request: NextRequest) {
  const cookie = request.headers.get("cookie");
  if (!cookie) {
    return null;
  }

  try {
    const res = await fetch(new URL("/api/me", process.env.NEXT_PUBLIC_URL), {
      headers: { Cookie: cookie },
      cache: "no-cache",
    });

    if (res.status === 200) {
      return res.json() as Promise<Serialized<SanitizedUser>>;
    } else {
      return null;
    }
  } catch {
    return null;
  }
}

export async function middleware(request: NextRequest) {
  if (request.nextUrl.pathname !== "/login") {
    const user = await getUser(request);
    if (!user) {
      if (request.method === "POST" || request.method === "PUT") {
        return new NextResponse("Not Authorized", { status: 401 });
      } else {
        const url = new URL("/login", process.env.NEXT_PUBLIC_URL);
        if (!["/login"].includes(request.nextUrl.pathname)) {
          url.searchParams.set("redirectTo", request.url);
        }
        return NextResponse.redirect(url);
      }
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/((?!api|_next/static|_next/image|favicon.ico|robots.txt|images).*)",
  ],
};


Any ideas or suggestions to figure this out would be much appreciated.

1 Reply

Atlantic menhadenOP
When trying to log-in, the URL changes but the page doesn't update.