13
votes

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?

2

2 Answers

6
votes

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.

3
votes

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>
  );
}