Next.js App Router using optional URL params

I am currently working on a project that should support various types of URL parameters. In Next.js, I am using the App Router, so only “next/navigation” is functional for me, not “next/router”.

I aim to construct my URL in the following format:

/Surveys/(shortname)/id/Report

Here, both ‘shortname’ and ‘id’ are variables. However, ‘id’ is always present in the URL, while ‘shortname’ is optional. For instance:

/Surveys/helloworld/123/Report

and

/Surveys/123/Report

Both URLs should direct me to the same page, where I have:

<h1>Survey shortname: helloworld</h1>
<p>ID: 123</p>

Or, when there is no ‘shortname’:

<h1>Survey</h1>
<p>ID: 123</p>

My initial approach was to use the Optional Catch-all Segments provided by Next.js. However, this didn’t work out because [[…shortname]] must be the last part of the URL, and it is crucial for me to have ‘Report’ at the end.

Consequently, I considered working with slugs like [shortname] and [id] as folders. But this didn’t work out either because I couldn’t operate without ‘shortname’.

Next, I tried working with rewrite rules in my next.config.mjs. For example:

/** @type {import('next').NextConfig} */
const nextConfig = {
    async rewrites() {
        return [
            {
                source: '/Surveys/:shortname/:id/Reports',
                destination: '/Surveys/Reports/[...slugs]',
            },
        ];
    },
};

export default nextConfig;

The idea was to trick Next.js into believing that the catch-all is at the end. Unfortunately, this didn’t work out either.

I would appreciate any assistance you can provide. If u can give an example project, with an improved folder-structure and using tsx, I would be very grateful!