I am currently tackling a project that needs to accommodate different types of URL parameters. In my Next.js setup, I am relying on the App Router, which means only “next/navigation” is active for me, excluding “next/router”.
My goal is to structure my URL in this manner:
/Surveys/(shortname)/id/Report
Here, both ‘shortname’ and ‘id’ are variables. However, ‘id’ is a mandatory part of the URL, whereas ‘shortname’ is optional. For example:
/Surveys/helloworld/123/Report
and
/Surveys/123/Report
Both of these URLs should lead to the same page, where I display:
<h1>Survey shortname: helloworld</h1>
<p>ID: 123</p>
Alternatively, if there is no ‘shortname’:
<h1>Survey</h1>
<p>ID: 123</p>
Initially, I attempted to utilize the Optional Catch-all Segments feature in Next.js. However, this proved to be challenging as [[…shortname]] must be the final part of the URL, whereas I need ‘Report’ at the end.
Subsequently, I explored the idea of using slugs like [shortname] and [id] as directories. Unfortunately, this approach failed as I couldn’t proceed without ‘shortname’.
Next, I experimented with rewrite rules in my next.config.mjs file. For instance:
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: '/Surveys/:shortname/:id/Reports',
destination: '/Surveys/Reports/[...slugs]',
},
];
},
};
export default nextConfig;
The concept was to deceive Next.js into thinking the catch-all is positioned at the end. Unfortunately, this approach also did not yield the desired results.
I would greatly appreciate any guidance or examples you can offer. If you could provide a sample project with an enhanced folder structure using tsx, I would be extremely thankful!