Next.js: Using Router.push with custom routing

Created on 20 Feb 2017  路  6Comments  路  Source: vercel/next.js

I have some custom routing logic going on with express like this:

  server.get('/posts/:id', (req, res) => {
    return app.render(req, res, '/post', req.params)
  })

And when I use the router to push to this route:

    Router.push(`/posts/${id}`)

I get a 404. When looking at the server logs I see this:

GET /_next/-/pages/posts/recBhAOprhFeugy0z 404 13.273 ms - 43621

And when I refresh on that route, I get this:

GET /posts/recBhAOprhFeugy0z 200 700.074 ms - 861132

So perhaps I shouldnt be using Router.push, with custom routing but I just wanted to check in about that.

Most helpful comment

interesting... might be a good idea to put include something like this in the express example.

All 6 comments

For that, you need to do:

Router.push(`/post?id=${id}`, `/posts/${id}`)

Check the Router.push() docs.

interesting... might be a good idea to put include something like this in the express example.

@ccorcos Good idea.

Sorry for hitting up a closed post. @ccorcos - I'm trying basically the same thing you've done. When I try to access /path/someparam as a direct url, I also get 404. Was there anything additional you did to make this work?

if you have a directory structure that looks like this:

/pages
    /post

Then you the post page will get query params as props in getInitialProps. That's why the first argument to Router.push should have query params. The second argument can be the actual path.

Cool, thanks

Was this page helpful?
0 / 5 - 0 ratings