2

I'm currently working with Next.js 14 and encountered an issue where the Link tag does not seem to prefetch data. Specifically, in the network tab of the developer tools, the preview shows {} instead of the expected JSON response. I'm using getServerSideProps and Page routes

I am expecting that the Link tag will prefetch the data and display the JSON data in the network tab. However, with Next.js 14, it doesn't seem to work as expected. The network tab shows an empty preview {} instead of the JSON data.

Has anyone else encountered this issue? Is there a new configuration or a different approach required in Next.js 14 to ensure that the Link tag prefetches JSON data correctly when using getServerSideProps?

Any insights or solutions would be greatly appreciated.

Additional Information:

Next.js version: 14 Node.js version: v18.17.0

3 Answers 3

1

This solution might help you!

The x-middleware-prefetch header is used by Next.js when it prefetches data in the background, typically to optimize page transitions.

By removing the x-middleware-prefetch header, you force Next.js to treat the prefetch request as a normal request, which can resolve this issue

Create a new file in your project root (or wherever your middleware files are located) named middleware.js

// middleware.js
import { NextResponse } from 'next/server';

export async function middleware(request) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.delete('x-middleware-prefetch');

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
}

This middleware will now run for every request in your Next.js application.

Sign up to request clarification or add additional context in comments.

Comments

0

Remove x-middleware-prefetch from the Next JS header.

Add this to middleware.jsx file.

    export async function middleware(NextRequest) {
    const requestHeaders = new Headers(NextRequest.headers);
    requestHeaders.delete('x-middleware-prefetch');
    const response = NextResponse.next({
        request: {
            headers: requestHeaders,
        },
    });
    return response;}

Comments

-1

I'm having the same issue.

The strange part is that be removing the header x-middleware-prefetch it's able to get the json, but after clicking the Link component, the page does not load (stays blank).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.