Nextjs dynamic routing exclude

Viewed 3226

Is there a way of excluding some dynamic routs in next.

Header component:

export const DynamicCatPageLinks = () => {
  const router = useRouter();

  const relPath = router.route
  const { tv } = router.query


  return (
    <Query query={CategoryList}>
      {({ loading, error, data }) => {
        if (loading) return <h2>Loading...</h2>;
        if (error) return <h1>Error fetching the post!</h1>;
        return (
          <>
            {data.category.map(cat => (
              <li key={cat.id}>
                <Link href=
                    {`/${tv}/category/page/${cat.slug}`}
                >
                  <a category={cat.slug}>{cat.name}</a>
                </Link>
              </li>
            ))}
          </>
        );
      }}
    </Query>
  );
};

Page Hierarchy

-pages
  -[tv]
   -category
   ...

So the url is: [tv]/category/page/...

Is there a way of limiting the values that can be passed to the [tv] route

So that the url can be, example:

television1/category/page/...
television2/category/page/...
television3/category/page/...
...

But if you do something like this: unknown/category/page/...

It renders a different page like 404 as example?

Thank you.

1 Answers

There is an RFC to allow custom Routes and regex with NextJS router

For now you can get the value in your component rendering and redirect if it doesn't fit the list of your whitelisted params

To do that you can create a custom hook so that you don't have to duplicate the logic

const whiteList = ['television1', 'television2, 'television3'];
const useWhiteListParams = () => {
   const router = useRouter();
   const { tv } = router.query;
   useEffect(() => {
       if(!whiteList.includes(tv)) {
           router.push(/404);
       }
   }, [tv])

}
Related