Next.js Discord

Discord Forum

Dynamic route fallback if param isn't available

Unanswered
Himalayan posted this in #help-forum
Open in Discord
HimalayanOP
I'm not sure if this is possible or not but thought I'd ask πŸ™‚

I have the following dynamic route set up to and was considering the possibility of a redirect/fallback if title wasn't available to display the page (and url) based on the id.

For example, both the following URL's would show the product:

https://www.website.com/product/the-title/ID000001
https://www.website.com/product/D000001

If so, how would this be set up in Next?

2 Replies

@Himalayan I'm not sure if this is possible or not but thought I'd ask πŸ™‚ I have the following dynamic route set up to and was considering the possibility of a redirect/fallback if `title` wasn't available to display the page (and url) based on the `id`. For example, both the following URL's would show the product: https://www.website.com/product/the-title/ID000001 https://www.website.com/product/D000001 If so, how would this be set up in Next?
you could try this
pages/product/[...params].tsx
then inside getServerSideProps
export const getServerSideProps: GetServerSideProps = async ({ query }) => {
  const id = query.params?.[1] || query.params?.[0];
  return {
    props: {},
  };
};

or with useRouter
export default function Page() {
  const router = useRouter();
  const id = router.query.params?.[1] || router.query.params?.[0];

  return <div>{id}</div>;
}
HimalayanOP
Thanks, let me give that a try πŸ™‚