1

I'm trying to do a redirect on every page if a certain condition is true using Nextjs middleware.

For some reason, whenever the matcher in middleware.ts matches a page, all props from getServerSideProps on that page are undefined when they reach the client side. When I remove pages from the matcher regex, they work as expected with the correct values.

Middleware.ts

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export default async function middleware(req: NextRequest) {
  return NextResponse.next();
}

export const config = {
  matcher: ['/(tag|about)(.)*'],
};

How can I make sure getServerSideProps still fires on pages that also trigger the middleware function?

(getServerSideProps is firing, and I see the correct values in the terminal, but I'm still getting undefined on the client-side specifically)

enter image description here

kennsorr
  • 292
  • 3
  • 20

2 Answers2

0

I tried reproducing this. But it just works fine for me. Please update your Next.js version to the latest. In case you are using app directory. getServerSideProps is not for the app directory. For app directory, you do data fetching inside the React Server Components.

https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts#data-fetching

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
-1

To make sure getServerSideProps still runs and the props are available on the client-side when using Next.js middleware, you can edit the middleware code as follows:


    import { NextResponse } from      'next/server';
    import { renderToString } from 'react-dom/server';
    import type { NextRequest } from 'next/server';

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

  const renderedPage =    renderToString(response.component);
  const serializedProps =       JSON.stringify(response.props);

  response.headers.set('Content-Type',     'text/html');
  response.body =    response.body.replace('<div    id="__NEXT_DATA__"></div>',    `<script>window.__NEXT_DATA__ =            ${serializedProps};</script>`);

    return response;
    }

    export const config = {
    matcher: ['/(tag|about)(.)*'],
    };

This modified code intercepts the response, serializes the props from getServerSideProps, and injects them into the HTML so that they are available on the client-side.

Good luck