Next.js Discord

Discord Forum

How to execute fetch request in middleware

Unanswered
American Shorthair posted this in #help-forum
Open in Discord
American ShorthairOP
Hi, I have recently embarked on a new learning project with Next.js 14 using App Router.

I am trying to execute a GET fetch request, and depending on the data in the response of the fetch request, it will depend what I do next.

I have used the example of using a fetch request provided in the docs (https://nextjs.org/docs/app/building-your-application/routing/middleware#waituntil-and-nextfetchevent), but changing POST to GET and removing the body. Here’s the code:

export default async function middleware(req: NextRequest, event: NextFetchEvent) {
  event.waitUntil(
    fetch('ENDPOINT_HERE', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    }),
  );
 
  console.log('NEXT RESPONSE', NextResponse.next());
 
  return NextResponse.next();
}

But when logging the response, the body is null.

Is anyone able to provide me with a working example? Or can you spot anything that I am doing wrong?

Or is there another way that I should be doing this?

Please let me know if I have missed anything that may be of help!

6 Replies

@Ray hi, I don't see you are sending the body in the fetch request?
American ShorthairOP
Hi, I am trying to make a GET request instead of a POST request. That’s why I am not sending a body in the request
so the the body is null?
btw, if you want to do something depend on the data from the fetch response, you shouldn't use waitUntil
export default async function middleware(req: NextRequest, event: NextFetchEvent) {
  const res = await fetch('ENDPOINT_HERE', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
  if (res.ok) {
    console.log('NEXT RESPONSE', NextResponse.next());
   
    return NextResponse.next();
  }
}

do this instead