title: Dynamic routing with next export mode
body: <p>We're using Next.Js in <a href="https://nextjs.org/docs/advanced-features/static-html-export" rel="nofollow noreferrer">next export mode</a> (static HTML export), and we need advanced dynamic routing.</p>
  <p>Our routes will look like <code>/[config1]/[config2]/[optionalConfig?]/page</code>, where one segment is optional and the page names are fixed. For example <code>a/b/c/page1</code> or <code>a1/b1/page2</code>. The pages need the configuration segment data to render.</p>
  <p>I haven't found any way to do this with the <a href="https://nextjs.org/docs/routing/dynamic-routes" rel="nofollow noreferrer">built-in routing</a>. I can do <code>/pages/[config1]/[config2]/page1.tsx</code>, but that optional segment seems to be an issue. Note that a custom server does not appear to be an option, as we have to use next export mode due to other constraints.</p>
  <p><strong>NOTE:</strong> We don't know the paths at build time; they represent part of our runtime configuration. This <em>has</em> to use client-side routing. (We <em>do</em> know the finite set of pages - say page1 ... page10 - but the routes to those pages will vary.)</p>
  <p>I've tried switching to React Router, setting <code>useFileSystemPublicRoutes: false</code> and adding routes to <code>pages/_app.tsx</code> (Custom App). That <em>almost</em> works, but I see many 404s for <code>on-demand-entries-utils.js</code> in the console as well as some &quot;Possible EventEmitter memory leak detected&quot; warnings (in development mode).</p>
  <p>Valid solutions (must work 100% client-side):</p>
  <ul>
  <li>Way to do this with built-in routing</li>
  <li>Example of integrating React Router with Next.Js</li>
  <li>Alternative library (I've looked at <a href="https://github.com/fridays/next-routes" rel="nofollow noreferrer">next-routes</a> but that hasn't been updated in 3 years)</li>
  </ul>
  <p><strong>UPDATE</strong></p>
  <p>We may be able to eliminate the requirement of an optional segment. However, it appears that we have to implement <code>getStaticPaths</code> and specify all of the routes. For example:</p>
  <p><strong>pages/[config]/foo.tsx</strong></p>
  <pre><code>export async function getStaticPaths() {
    // Runs at build time
    return {
      paths: [{ params: { config: 'xyz' } }],
      fallback: false,
    };
  }
  
  export async function getStaticProps(context) {
    return {
      props: {},
    };
  }
  
  export default function FooPage(): JSX.Element {
    return &lt;div&gt;FOO&lt;/div&gt;;
  }
  </code></pre>
  <p>This will generate</p>
  <pre>
  ┌ ○ /
  ├   /_app
  ├ ● /[config]/foo
  ├   └ /xyz/foo
  </pre>
  <p>The issue is that <em><strong>we do not know the config at build time.</strong></em></p>
  <p>We need dynamic client-side routing. We'd like to stay with Next.js, as <em>eventually</em> we may be able to use SSR, but that's not an option at the moment.</p>