Nextjs How to map multiple routes to one page?
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.
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> );}