boosted_duck
boosted_duck

Reputation: 508

Need help about nextjs dynamic url

I am having this problem that whenever i try to visit the page localhost:3000/blog/test directly it returns a 404 error. But whenever i try to visit it using <Link> component it works fine.

This is my code <Link href={{ pathname: '/blog', query: {slug: 'test'} }} as="/blog/test"><a className="nav__link">Blog</a></Link>

and i have a file blog.js in my pages folder.

Upvotes: 1

Views: 2884

Answers (2)

Ghost
Ghost

Reputation: 55

You'll have to use now.json to set up your routes. Also it is important to note that it's now that builds the route so visiting it on the client side wont work if you are using localhost. Build your project with now and it should work.

Also the "as" parameter would be as={{ pathname:/user/manage/${variable}}}

Upvotes: 0

Matthew Rapati
Matthew Rapati

Reputation: 5696

What's happening is that on the client, with the Link component, you are creating a link to the blog.js page by setting "/blog" as the pathname.

When you go directly to the URL/blog/test, Next.js will try to render the page on the server and to do so will look for the file /pages/blog/test.js. That file doesn't exist, and Next.js doesn't know that you want to load the blog.js page and set query.slug to to the second part of the URL.

To do this, you need to map that route on the server to load the page you want, and pull the params you want out of the URL.

The Next.js docs cover this in Server Side Support for Clean URLs by using express to setup a custom server.

You can view the full code to get it working there, but your custom route will look something like this:

server.get('/blog/:slug', (req, res) => {
  const actualPage = '/blog'
  const queryParams = { slug: req.params.slug }
  app.render(req, res, actualPage, queryParams)
})

Upvotes: 4

Related Questions