next-routes icon indicating copy to clipboard operation
next-routes copied to clipboard

How to implement exact route like react-router-dom?

Open hrahimi270 opened this issue 5 years ago • 4 comments

Hello there. Thanks for what you're doing 👍. I need to config my routes like these:

/post => 404 page
/post/:id/:title => show the post page and fetch data with ajax!
/post/:id => 404 page

How can I implement these? Can you guys help me, please?

hrahimi270 avatar Jul 11 '19 17:07 hrahimi270

In the routes.js file. Try this:

const routes = require('next-routes')

module.exports = routes()
.add('/post/:id/:title', 'postPage')

In your post page you will be able to get the id & title as query. ( if you don't add the other two routes those won't be mapped to anything.

shivashp avatar Jul 19 '19 04:07 shivashp

Thank you @shivashp. I did the same. But when I open post page with /post/:id or /post, the same page initialized with next.js. I want to automatically redirect them to not found page. Do you think if I config these pages, I mean /post/:id and /post to open the not found page, it will be cool?

hrahimi270 avatar Jul 19 '19 06:07 hrahimi270

@hrahimi270 I don't think that's a good idea of having routes definition for routes you won't have. for simplicity sake you can rename your post file to something like postPage. So that next doesn't pick up /post from filesystem. This is also not the ideal solution but works if your problem is only with post keyword.

shiva-wizeline avatar Aug 09 '19 03:08 shiva-wizeline

try this in server.js before server.use(routes.getRequestHandler(app))

server.get('/post', (req, res) => {
  return app.render(req, res, '/404', req.query)
})

guangteyangdd01 avatar Apr 09 '20 09:04 guangteyangdd01