1

I'm trying to use fetch inside a middleware handler in NextJS such that I can authorize access to /internal/** - there will be a lot of pages which are meant only for internal use, so using getServerSideProps for every page is not ideal.

I have the following code in src/middleware.ts

import { NextRequest, NextResponse, userAgent } from "next/server";

export async function middleware(req: NextRequest) {
  const { origin, pathname } = req.nextUrl;

  if (pathname.startsWith("/internal")) {
    console.log(origin + "/api/auth/user/get");
    const res = await fetch(origin + "/api/auth/user/get")
    const data = await res.json();

    console.log("middleware", req.cookies.get("krl_auth_cookie")?.slice(0, 5) + "");
    console.log("middleware", data)
  }

  if (pathname.includes("_next")) {
    return NextResponse.next();
  }

  return NextResponse.next();
}

The fetch-url does not see the cookie, even if I add credentials: "include" as an option to fetch.

If I perform a fetch, in the browser console, to the same url as in the fetch call the result is as expected, but console.log("middleware", data) prints {}.

Is it not possible to use fetch in middleware? - I don't get any errors thrown at me while trying to do so.

pietrrrek
  • 33
  • 8
  • Try to explicitly pass the cookie in the fetch request (similar to what's done for API routes: https://stackoverflow.com/questions/69057271/why-are-cookies-not-sent-to-the-server-via-getserversideprops-in-next-js). I assume the Edge runtime doesn't automatically send cookies like the browser does. – juliomalves Jul 16 '22 at 12:45

0 Answers0