Search code examples
reactjsnext.jsmiddleware

How to send a POST/GET request from a middleware file in Next.js?


I am trying to send a GET request directly in the middleware file but unfortunately I am getting a weird error message. This is my middleware file:

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

export async function middleware(request: NextRequest) {
  const response = NextResponse.next();

  await fetch(new URL("http://api.tvmaze.com/search/shows?q=postman").href, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });

  return response;
}

Unfortunately, when I try that, the error message is:

[TypeError: Cannot delete property 'Symbol(set-cookie)' of #]

Do you have any idea why I'm getting this error message?


Solution

  • I found out how to do it. Here is an example how we send a POST request.

    fetch(new URL("/endpoint", "http://yourdomain.com"), {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        type: "PAGE_REQUESTED",
      })
    });
    

    Sending GET request is simple as well - just change method: "POST" to method: "GET", and remove the body.

    We do not await the request because we don't want it to delay our application. So if this a GET request just use .then in order to get the data