Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs How to map multiple routes to one page?

I have a page called blog in my nextjs version 9.

Next create a route /blog for my page. Now I want to have these routes to be mapped to the same blog page and consequently the blog component:

1. /blog/cat1/gold
2. /blog/cat2/silver
3. /blog/cat3/bronze

Actually, I want to use them as query parameters in the route but I don't want to follow this format:

1. /blog?cat=cat1&color=gold
2. /blog?cat=cat2&color=silver
3. /blog?cat=cat3&color=bronze

I used next/router asPath but it is completely client-side and by reloading it returns 404!

In nextjs 9 dynamic routing has provided which may help me but the thing is I want to have only one component and different routes.

Do you have any ideas?

like image 298
Afsanefda Avatar asked Aug 20 '19 11:08

Afsanefda


2 Answers

You can do this with Next's dynamic routers. Just create a folder for blog-posts and add a dynamic page under it like this:

  /pages/blog/[...slug].tsx

Now on your [...slug].tsx will catch all paths, no matter in what depth. And you can catch the path params from the router's query -field. Try this with any path under /blog/**/* -path and it will list path elements:

const Blog = () => {

  const { 
    query: { slug } 
  } = useRouter(); 

  return (
    <ul>
      {query.slug.map(value => <li key={value}>{value}</li>)}
    </ul>
  );
}

like image 71
Ville Venäläinen Avatar answered Oct 19 '22 17:10

Ville Venäläinen


You didn't specify your web server, so I will give an example using expressjs.

const app = next({ dev })

app.prepare().then(() => {
   const server = express();
   server.get("/blog/:cat/:color", (req, res) => app.render(req, res, `/blog`));
})

If you need to access the value in the page, you can use getInitialProps to get the value by accessing req.params.cat and req.params.color.

Another way is by passing the value directly when calling app.render function:

app.render(req, res, '/posts', { cat: req.params.cat, color: req.params.color })

Here is the example.

like image 28
Darryl RN Avatar answered Oct 19 '22 16:10

Darryl RN