Next.js Discord

Discord Forum

Get Request 200 but Response Body Empty

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
Hi everyone, I am making requests to my next js server which makes a request to my rails API. Some times the request (GET) returns a 200 status but the response body is empty. Does anyone have any idea what could be the cause of this? Is it a cache issue if I make the same request twice? Is it a content length header issue? I dont know how to debug this. This is my code:

api > [...proxy]
import { auth } from "@/auth";
import { makeApiProxy } from "@growi/sdk/api/server";
import { NextRequest } from "next/server";

export const runtime = "edge";

// @ts-ignore
const handler: (req: NextRequest) => Promise<Response | undefined> =
  makeApiProxy({
    baseApiUrl: process.env.GROWI_API_URL!,
    apiHeaders: (req) => {
      return {
        "Investigate-User": req.cookies.get("investigate_user")?.value || "",
        "App-Name": "web",
      };
    },
    getAuthToken: async () => {
      const session = await auth();
      return session?.user?.payload?.token;
    },
  });

export {
  handler as GET,
  handler as POST,
  handler as PUT,
  handler as DELETE,
  handler as PATCH,
};

5 Replies

Transvaal lionOP
And here is my makeApiProxy file (PART 1):
import { NextRequest } from "next/server.js";

export interface MakeAPIProxyParameters {
  baseApiUrl: string;
  apiHeaders?:
    | HeadersInit
    | ((req: NextRequest) => Promise<HeadersInit> | HeadersInit);
  getAuthToken?: () =>
    | (string | null | undefined)
    | Promise<string | null | undefined>;
}

const makeForwardUrl = ({
  requestUrl: reqUrl,
  baseApiUrl,
}: {
  requestUrl: string;
  baseApiUrl: string;
}) => {
  const requestUrl = new URL(reqUrl);
  const forwardUrl = new URL(baseApiUrl);

  forwardUrl.pathname = requestUrl.pathname;
  forwardUrl.search = requestUrl.search;

  return forwardUrl;
};

const HEADERS_TO_DELETE = ["content-length", "connection", "cookie"];
const HEADERS_TO_ADD = { "Content-Type": "application/json" };

const makeForwardHeaders = async ({
  apiHeaders,
  request,
}: {
  apiHeaders: MakeAPIProxyParameters["apiHeaders"];
  request: NextRequest;
}) => {
  const headers = new Headers(request.headers);

  HEADERS_TO_DELETE.forEach((h) => headers.delete(h));

  Object.entries(HEADERS_TO_ADD).forEach(([k, v]) => {
    headers.set(k, v);
  });

  const extraHeaders = new Headers(
    typeof apiHeaders === "function" ? await apiHeaders(request) : apiHeaders
  );

  extraHeaders.forEach((val, key) => {
    headers.set(key, val);
  });

  return headers;
};
PART 2
export const makeApiProxy = ({
  apiHeaders,
  baseApiUrl,
  getAuthToken,
}: MakeAPIProxyParameters) => {
  return async (req: NextRequest) => {
    const forwardHeaders = await makeForwardHeaders({
      request: req,
      apiHeaders,
    });

    const token = await getAuthToken?.();

    if (token) {
      forwardHeaders.set("Authorization", `Bearer ${token}`);
``    }
``
    const forwardUrl = makeForwardUrl({ requestUrl: req.url, baseApiUrl });

    const body = req.body ? await req.json() : null;

    if (process.env.NODE_ENV === "development") {
      // console.log("AUTHENTICATED?", !!token);
      // console.log("URL", forwardUrl.toString());
      // console.log("METHOD", req.method);
    }

    try {
      const res = await fetch(forwardUrl, {
        ...req,
        headers: forwardHeaders,
        method: req.method,
        // body: req.method !== "GET" ? body : null,
        body: body ? JSON.stringify(body) : null,
        cache: "no-store",
        // @ts-ignore
        // duplex: "half",
      });

      console.log("RICHARD", JSON.stringify(res.body, null, 2));
      console.log("HI", JSON.stringify(res, null, 2));

      return new Response(res.body, {
        status: res.status,
      });
    } catch (e) {
      console.log("Error in API proxy:");
      console.log(e);
    }
  };
};
The res.status is 200 and the res.body is just {}
I am making a GET request
Transvaal lionOP
can anyone help??