next.js: New experimental dynamic routing breaks zone support

Bug report

When using experimental dynamic routes (#7432) in a zoned app. I get this error in the browser:

Your `<Link>`'s `as` value is incompatible with the `href` value. This is invalid

Describe the bug

In order to find the query parameters, href and as are matched against each other. But the current implementation seems to be too strict.

see https://github.com/zeit/next.js/blob/21fae5262f2dada7a229e6dd2831639d330ff746/packages/next-server/lib/router/router.ts#L274-L281

To Reproduce

See https://github.com/Xiphe/next-dynamic-route-in-zone

  1. Create a next app
  2. Add a proxy to have it mounted on a subpath (like http://localhost:3000/foo)
  3. Add a index page and a dynamic page (like pages/bar/$dyn.js)
  4. Try to link to the dynamic page from the index page
    <Link href="/bar/$dyn" as "/foo/bar/baz"><a>Baz</a></Link>
    
  5. Click the link in the browser

Expected behavior

I want to use dynamic routes in a zoned app, so the above Link-code should not throw.

System information

  • OS: macOS
  • Browser: chrome
  • Version of Next.js: 8.1.1-canary.43

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 11
  • Comments: 24 (11 by maintainers)

Most upvoted comments

If you do not want to incorporate the zone name into your pages directory then you can use the following monkey patch to work around this issue (Note: I store the zone/base path in the next public runtime config but you can hardcode it):

import getConfig from 'next/config';
import * as routeMatcher from 'next/dist/next-server/lib/router/utils/route-matcher';

const { publicRuntimeConfig } = getConfig();

if (!routeMatcher._patched) {
  routeMatcher._patched = true;
  routeMatcher._getRouteMatcher = routeMatcher.getRouteMatcher;
  routeMatcher.getRouteMatcher = function getPatchedRouteMatcher(routeRegex) {
    const originalMatcher = routeMatcher._getRouteMatcher(routeRegex);

    return function patchedRouteMatcher(route) {
      if (route.indexOf(publicRuntimeConfig.basePath) === 0) {
        route = route.substr(publicRuntimeConfig.basePath.length);
      }

      return originalMatcher(route);
    }
  }
}

I’m glad that @Xiphe came to a conclusion for their personal project, but downstream dependencies like next-i18next need to be able to insert subpaths without making modifications to the filesystem.

See https://github.com/isaachinman/next-i18next/issues/413.

Can we reopen this issue?

Good news: I have an updated with-zones example that uses Next.js 9 dynamic routing and works perfectly with both now dev (two Next.js apps running behind a proxy together, in a multi-zone setup) and next dev (a single Next.js app running separately, serving just its own routes).

I have to catch some sleep but will push the example tomorrow.