next-routes
next-routes copied to clipboard
How to implement exact route like react-router-dom?
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?
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.
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 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.
try this in server.js
before server.use(routes.getRequestHandler(app))
server.get('/post', (req, res) => {
return app.render(req, res, '/404', req.query)
})