regexnext.jsurl-routing

Forward pages not matching a regexp to another backend in NextJS


I want to integrate a NextJS app with a Laravel application.

The NextJS app is responsible for the routes

/
/node/123456789
/way/123456789
/relation/123456789
/install

Where 123456789 any numbers.

The Laravel application should be responsible for all other URLs.

The all-page-routing of the NextJS app looks like this:

  const [osmtype, osmid] = all;
  const shortId =
    osmtype && osmtype.match(/^node|way|relation$/)
      ? osmtype.substr(0, 1) + osmid
      : id;

  if (!shortId) {
    return notFound();
  }

I am trying to do this with a rewrite in next.config.js

Currently I have negative lookahead regexp like this:

  rewrites: () => {
    return [
        {
          source: '/((?!node|way|relation|install):path*)',
          destination: `http://pages.example.com/:path*`,
        }
      ]
  }

But this would not match and call the 404 page of the NextJS app.

I also tried

source: '/((?!node|way|relation|install)):path*',

Here I got a bit closer.

Calling something like http://nextjsapp.example.com/bar

Would lead to a GET /r in the Apache access log of pages.example.com - so somehow :path* only was catching the last letter.

How can I make it match the full path and pass it to the Laravel backend?

Additionally I tried the fallback rewrite, but this does not seem to work due to the nature of the routing in the NextJs app - I still would get the 404 error.


Solution

  • The * was too much - also I don't know where the backticks came from in destionation. This works:

    source: '/((?!node|way|relation|install):path)',
    destination: 'http://pages.example.com/:path',
    

    EDIT: If this should also work for subpaths, use

    source: '/((?!node|way|relation|install)):path(.*)',
    destination: 'http://pages.example.com/:path',