blog
contact
hire me

How to get query string parameters from the URL in Next.js

nextjs

Someone left a message on my site about How to get query string parameters from the URL in Next.js.

They were using next/link to build a button while passing a query to the new page, the only problem was that the new page wasn’t picking up the query.

import Link from "next/link";

export default () => (
  <>
    <Link
      href={{
        pathname: "/about",
        query: { name: "TIM" },
      }}
    >
      <a>Read More</a>
    </Link>
    to read more
  </>
);

There are a number of ways to do this depending on how you’re rendering the page but the first solution that comes to mind is the useRouter() hook that Next has built it.

If we recreate this dev’s question by creating an about route in next js, then we’ll have our default page as index.js.

We have a barebones set up here and we’ll import useRouter from next/router.

From here we can destructure the param in the url using router.query. For this example our param will be name, so we’ll strip name out.

We can then show what that is by placing it in our page code and we’re good to go.

import { useRouter } from "next/router";

const About = () => {
  const router = useRouter();
  const { name } = router.query;

  return (
    <>
      <h1>About Page </h1>
      <h2>Query = {name}</h2>
    </>
  );
};

export default About;

Now if we’re using Server Side Rendering we can get the query param from the context object and pass that to our page as a prop.

The setup is a little different.

We use the ServerSideProps function and grab the query key from the context object using destructuring.

On that key, we can then grab the name key which contains the param we’re looking for.

export async function getServerSideProps({ query }) {
  const { name } = query;

  /* 
    Pass the name param to the page
  */
  return { props: { name } };
}

/* 
    Simple example.
    The context object has a lot of info.
*/
context = {
  query: { name: "TIM" },
};

We can then pass this param to the page as a prop

const About = ({ name }) => {
  return (
    <>
      <h1>About Page </h1>
      <h2>Query = {name}</h2>
    </>
  );
};

export default About;
export async function getServerSideProps({ query }) {
  const { name } = query;

  return { props: { name } };
}