Get query params in Next.js


Getting query parameters in Next.js is very simple, but is done differently on the client and on the server.

Getting query parameters on the client

To get the query parameters on the client, there are several ways exposed by the next/router module. The two most useful are the useRouter hook and the withRouter HOC. For example,

import { useRouter, withRouter } from "next/router";

const User = () => {
  const {
    query: { id },
  } = useRouter();
  return <span>The user id is {id}</span>;

// or

const User = withRouter(({ router: { query: { id } } }) => (
  <span>The user id is {id}</span>

You should be careful when restructuring the query parameters if they are optional since you'll get an undefined error trying to read the property value.

Getting query parameters on the server

On the server you can get the query parameters inside of the getIntitialProps function. They can be extracted out of the http request in a way similar to an express handler:

const UserPage = ({ id }) => <span>The user id is {id}</span>;

UserPage.getInitialProps = ({ query: { id } }) => {
  return { id };

Again, be sure that if you are destructuring inline without checking the existence of the parameter that it should be required in your app (eg your app only links to that route with the parameter).

Promoting query parameters to route parameters

Using the newly added dynamic routes in Next.js 9 you can transform a url like: /users?id=user_12345 into /users/user_12345. To do this create a file in the pages directory: /pages/users/[id].js where id is the name of the parameter you want to reference. Then in the request query either on the client or the server you can get the id as above.

Where are the docs?

Here is the documentation on routing for Next.js. One of the key benefits of Next is that routing is made so simple by effectively being specified by the file structure. Most routing cases can be handled in this way and it makes Next a great choice for serverless as well. You can of course still run Next as a monolith using an express server, which would give you full control over the routing if you had a need for that control. But we would generally recommend sticking with the Next.js routing paradigm because it will be the most maintained / optimized going forward.