Next.js: Retrieve URL Params from Dynamic Routes

Last updated on March 4, 2022 A Goodman Loading... Post a comment

You can extract segment data from a dynamic route in Next.js by using the useRouter hook. Let’s say the pages folder of a Next.js project has a structure as follows:

.
├── _app.js
├── api
├── index.js
└── users
    └── [uid].js

Then we can access a URL with a specific uid like so:

/users/123

We can get uid and display it like this:

import { useRouter } from "next/router";

export default function User() {
  const router = useRouter();
  const query = router.query;

  const uid = query.uid;

  return (
    <div style={{ padding: 40 }}>
      <h1>User Page</h1>
      <h2>uid: {uid}</h2>
    </div>
  );
}

Demo:

You can do the same with nested dynamic routes.

Further reading:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like