NextJs localized rewrites with query parameters reloads the browser and throws failed to load script error

1.5k Views Asked by At

I'm facing an issue while using rewrites and query parameters. I'll describe it further below. if I've lost you at any point during the explanation feel free to ask for a clarification.


Expected result

What I'm trying to achieve is localizing a next/link and passing a query paramter to fill in the dynamic part of the url.


The setup

I have my setup split into a few files, a pathnames.js which holds all the paths and translations. (Won't show the whole file just the neccesary parts)

// The predefined consts for the pathnames
export const pathnames = {
  STOREFINDER: 'stores',
  STOREFINDER_DETAIL: '/stores/[id]',
};

// The localized part of the pathnames
export const localizedPathnames = {
  // This works
  [pathnames.STOREFINDER]: {
    nl: '/winkels',
    fr: '/magasins',
  },
  // This works half (further explanation below)
  [pathnames.STOREFINDER_DETAIL]: {
    nl: '/winkels/[id]',
    fr: '/magasins/[id]',
  },
};

And then the next.config.js where I define the rewrites. (Won't show the whole file just the neccesary parts)

async rewrites() {
  return [{
      source: '/winkels',
      destination: '/stores',
   },
   {
      source: '/magasins',
      destination: '/stores',
   },
   {
      source: '/winkels/:id',
      destination: '/stores/:id',
   },
   {
      source: '/magasins/:id',
      destination: '/stores/:id',
   },  
]}

This is how I make a localized link


<Link
    href={getLocalizedRoute(pathnames.STOREFINDER_DETAIL, locale, {
        query: { id: name },
    })}
    passHref
>
    <Button className="store-info-card-cta" color="secondary">
        {formatMessage({ id: 'store_finder_search_result_details' })}
    </Button>
</Link>

Example return of getLocalizedRoute function

{
  "pathname": "/nl/winkels/[id]",
  "query": {
    "id": "lommel"
  }
}

Current result

Alright, that's the setup.

  1. Now whenever you press the link next will first throw an error that you can see on the screenshot below. Error message shown before routing event starts

  2. Then it will start 'reloading' the browser and continue routing to the correct path without an issue. Reloading image example

  3. On Production this works without the error, but you still see the browser reloading, which is not ideal.

  4. The only thing that works, is routing without the rewrites and localization and just routing to i.e.: /shops/lommel. Which is again, not ideal since the customer relies on localized urls.

<Link
    href={{
        pathname: `/${locale}/stores/[id]`,
        query: { id: name },
    }}
    passHref
>
    <Button className="store-info-card-cta" color="secondary">
        {formatMessage({ id: 'store_finder_search_result_details' })}
    </Button>
</Link>
0

There are 0 best solutions below