NextJS URL params like React-Router

For older version: < 9.x

You can use next/link's as feature:

<Link prefetch as={`/product/${slug}`} href={`/product?slug=${slug}`}>

Link on the browser will appear as /product/slug which internally maps to /product?slug=slug

You need to have a custom server for server-side mapping:

server.get("/product/:slug", (req, res) => {
  return app.render(req, res, "/product", { slug: req.params.slug })
})

For 9.x and higher

Next 9.x supports file system based dynamic routing. You don't need a custom server anymore.

Next.js supports creating routes with basic named parameters, a pattern popularized by path-to-regexp (the library that powers Express).

Creating a page that matches the route /product/:slug can now be achieved by creating a file in your pages directory named: pages/product/[slug].js.

Multiple dynamic URL segments are also supported!

./pages/blog/[blogId]/comments/[commentId].js
./pages/posts/[pid]/index.js

First import Router

import Router from 'next/router'

Then if you want to use it in a Link tag

<Link href={{ pathname: '/about', query: { name: 'Sajad' } }}>

If you want to use it in a function or after a callback

Router.push({
    pathname: '/about',
    query: { name: 'Sajad' },
  })

For anyone arriving late to this party, we now have dynamic routing in Next 9.

Which would allow for a url structure to be crafted like this by using the file structure, and without additional packages.

You could create a file pages/user/[id].js

With

import { useRouter } from 'next/router'

const User = () => {
  const router = useRouter()
  const { id } = router.query

  return <p>User: {id}</p>
}

export default User