Tofuu
Tofuu

Reputation: 65

Nextjs middleware rewrite page props sometimes undefined

Hope this finds yo well.

I'm working on a multilang website with translated URLs. I'm on Next.js 13.3 To handle the translated rotues i'm using a middleware. ( I have a large number of rewrites/redirects and the config ones entirely broke client side navigation )

When I navigate to an SSR page using next/link 5 times out of 10 the page loads correctly but the other 5 all the props are undefined. This only happens when there are rewrites meaning on locales other than english.

Here's how I'm handling the rewrites

 const rewrite: rewriteType | null = findMatchingRewrite(
    rewrites,
    `/${locale}${pathname}`,
  )
  
 if (rewrite !== null && rewrite.source !== rewrite.destination) {
    let destination = ''
    if (rewrite.params !== undefined) {
      destination = rewrite.destination.replace(
        /:(\w+)/g,
        (match, paramName) => rewrite?.params![paramName] || '',
      )
    } else {
      destination = rewrite.destination
    }

    rewrite.destination = destination
    
    return NextResponse.rewrite(new URL(rewrite.destination, req.url))
 }

The getStaticProps function could be as simple as this

export const getServerSideProps: GetServerSideProps = async () => {
 return {
      props: {
        test: 'test',
      },
    }
}

and the test prop will be undefined.

getServerSideProps itself seems to be running fine because I do see the data if I console.log but it doesn't make its way to the page

SSR pages on the other hand work totally fine

Is there something I'm missing?

EDIT: I suspect the same issue will happen with static pages during regeneration but i'm yet to confirm

EDIT 2: Replacing

 return NextResponse.rewrite(new URL(rewrite.destination, req.url))

with

  const url = req.nextUrl.clone()
    url.pathname = rewrite.destination

    return NextResponse.rewrite(url)

seems to have fixed the problem. Have to make sure but if it's the case all add this as an answer

Upvotes: 3

Views: 1017

Answers (0)

Related Questions