Optional Router Parameter for NextJS App Router

Optional Router Parameter for NextJS App Router

I am trying to achieve the following routing in this with AppRouter in NextJS.

/company/activity
/company/:cid/activity

I cannot use Optional Catch-all segment, as I will have more pages with same pattern. For example:

/company/employees
/company/:cid/employees

Alternative I can think of is using a static identifier, for example: /company/all/activity

When I see cid = "all" -> I need to treat this as /company/activity and deal accordingly.

This seems so common scenario and cannot find how to achieve this without this hack. Any suggestion is appreciated.

Answer

Take the file structure:

app/
├── company/
│   ├── activity/
│   │   └── page.tsx
│   └── [cid]/
│       └── activity/
│           └── page.tsx
components/
└── ActivityPage.tsx

componentpage.tsx

// components/ActivityPage.tsx
'use client';

import React from 'react';

export default function ActivityPage({ cid }: { cid?: string }) {
  return (
    <div className="p-4">
      <h1 className="text-2xl font-bold">
        {cid ? `Activity for Company: ${cid}` : 'Global Company Activity'}
      </h1>

      {/* Example content */}
      <p className="mt-4">
        {cid
          ? `Showing scoped activity data for company ID: ${cid}`
          : 'Showing all companies\' activity.'}
      </p>
    </div>
  );
}

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions