Next.js app in subfolder with basePath, how to make home page available outside of basePath?

Viewed 912

My Next.js application is running in the '/portal/' folder and basePath is set as follows:

module.exports = {
    basePath: '/portal'
}

Now I need index page of that application to be also available in site root (without basePath). So that both '/' and /portal/*' will be handled by Next.js app while other routes are handled by another web apps. On Nginx side root route is passed to Next.js app, but it isn't clear how to serve a page outside of basePath. I tried rewrites:

async rewrites() {
    return [
        {
            source: '/',
            destination: '/portal/',
            basePath: false
        },
    ];
},

but got an error: The route / rewrites urls outside of the basePath. Please use a destination that starts with `http://` or `https://` https://nextjs.org/docs/messages/invalid-external-rewrite Is it possible to serve one page outside of basePath or the only way is to remove basePath and change all paths and links in Next.js app manually?

1 Answers

Probably using Redirects could be helpful in your case.

module.exports = {
  basePath: '/portal',
  async rewrites() {
  return [
          {
              source: '/',
              destination: '/portal/',
              basePath: false
          },
      ];
  },
  async redirects() {
    return [
      {
        source: '/with-basePath', // automatically becomes /portal/with-basePath
        destination: '/another', // automatically becomes /portal/another
        permanent: false,
      },
      {
        // does not add /docs since basePath: false is set
        source: '/without-basePath',
        destination: '/another',
        basePath: false,
        permanent: false,
      },
    ]
  },
}
Related