Next.js Discord

Discord Forum

Empty response {} on adding x-middleware-prefetch in request header

Answered
Egyptian Mau posted this in #help-forum
Open in Discord
Egyptian MauOP
I'm using Next.js v14.2.5 and I noticed while sending a request to mysite.com/ with an additional header x-middleware-prefetch: 1, it returns an empty JSON object, whereas if I remove the header, I get the html response. I googled the issue and stumbled upon https://github.com/vercel/next.js/issues/52515. But I could not find anything conclusive. Does anobody know why this happens? Also, what are the steps to fix this/avoid this behaviour? A sample response header is in the thread. Any help will be appreciated.
Answered by Egyptian Mau
This is what I could come up with. Added a condition in the middleware. Not the best solution but it might work for some people.
export default function middleware(request) { const requestHeaders = new Headers(request.headers) if (requestHeaders.has('x-middleware-prefetch')) { requestHeaders.delete('x-middleware-prefetch') return NextResponse.next({ request: { // New request headers headers: requestHeaders, }, }) } }
View full answer

2 Replies

Egyptian MauOP
Egyptian MauOP
This is what I could come up with. Added a condition in the middleware. Not the best solution but it might work for some people.
export default function middleware(request) { const requestHeaders = new Headers(request.headers) if (requestHeaders.has('x-middleware-prefetch')) { requestHeaders.delete('x-middleware-prefetch') return NextResponse.next({ request: { // New request headers headers: requestHeaders, }, }) } }
Answer