Search code examples
next.jsnext.js13nextjs14

show custom component Instead of 404 when there aren't params in Nextjs


In my Nextjs Project I have the /search route with dynamic params like this search/[...catType]

I want to show the AllProducts component when there aren't any params, I mean url just to be like : localhost:3000/search. By default it shows the not found page.

how can I handle it? the Page.tsx

import SearchAllProduct from "@/app/components/pagesComponents/search/allProducts/AllProducts";
import ThreeCategory from "@/app/components/pagesComponents/search/twoCategory/ThreeCategory";
import TwoCategory from "@/app/components/pagesComponents/search/twoCategory/TwoCategory";
import { Metadata } from "next";
import { notFound } from "next/navigation";

export default async function Search({
  params,
}: {
  params: { catType: string[] };
}) {
  const { catType } = params;

  const [catOne, catTwo, catThree, catFour] = catType;

  if (catType.length === 2) {
    return (
      /* @ts-expect-error Server Component */
      <TwoCategory catTwoId={catOne} catTwoName={decodeURI(catTwo)} />
    );
  }

  if (catType.length === 4) {
    /* @ts-expect-error Server Component */
    return <ThreeCategory catThreeId={catThree} />;
  }

  if (catType.length === 0) {
    /* @ts-expect-error Server Component */
    return <SearchAllProduct />;
  }

  return notFound();
}

Solution

  • add page.tsx in /search root and return AllProducts component from there. and in /search/[...catType]/page.tsx search for your query.

    enter image description here