[next.js] How can I get (query string) parameters from the URL in Next.js?

When I click on a link in my /index.js, it brings me to /about.js page.

However, when I'm passing parameter name through URL (like /about?name=leangchhean) from /index.js to /about.js, I don't know how to get it in the /about.js page.

index.js

import Link from 'next/link';
export default () => (
  <div>
    Click{' '}
    <Link href={{ pathname: 'about', query: { name: 'leangchhean' } }}>
      <a>here</a>
    </Link>{' '}
    to read more
  </div>
);

This question is related to next.js query-string

The answer is


Use router-hook.

You can use the useRouter hook in any component in your application.

https://nextjs.org/docs/api-reference/next/router#userouter

pass Param

import Link from "next/link";

<Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link>
Or
import Router from 'next/router'

Router.push({
    pathname: '/search',
    query: { keyword: 'this way' },
})

In Component

import { useRouter } from 'next/router'

export default () => {
  const router = useRouter()
  console.log(router.query);

  ...
}

Using Next.js 9 or above you can get query parameters:

With router:

import { useRouter } from 'next/router'

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

  return(<div>{id}</div>)
}

With getInitialProps:

const Index = ({id}) => {
  return(<div>{id}</div>)
}

Index.getInitialProps = async ({ query }) => {
  const {id} = query

  return {id}
}

url prop is deprecated as of Next.js version 6: https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md

To get the query parameters, use getInitialProps:

For stateless components

import Link from 'next/link'
const About = ({query}) => (
  <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)

About.getInitialProps = ({query}) => {
  return {query}
}

export default About;

For regular components

class About extends React.Component {

  static getInitialProps({query}) {
    return {query}
  }

  render() {
    console.log(this.props.query) // The query is available in the props object
    return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>

  }
}

The query object will be like: url.com?a=1&b=2&c=3 becomes: {a:1, b:2, c:3}


_x000D_
_x000D_
Post.getInitialProps = async function(context) {_x000D_
_x000D_
  const data = {}_x000D_
  try{_x000D_
    data.queryParam = queryString.parse(context.req.url.split('?')[1]);_x000D_
  }catch(err){_x000D_
    data.queryParam = queryString.parse(window.location.search);_x000D_
  }_x000D_
  return { data };_x000D_
};
_x000D_
_x000D_
_x000D_


For those looking for a solution that works with static exports, try the solution listed here: https://github.com/zeit/next.js/issues/4804#issuecomment-460754433

In a nutshell, router.query works only with SSR applications, but router.asPath still works.

So can either configure the query pre-export in next.config.js with exportPathMap (not dynamic):

    return {
      '/': { page: '/' },
      '/about': { page: '/about', query: { title: 'about-us' } }
    }
  }

Or use router.asPath and parse the query yourself with a library like query-string:

import { withRouter } from "next/router";
import queryString from "query-string";

export const withPageRouter = Component => {
  return withRouter(({ router, ...props }) => {
    router.query = queryString.parse(router.asPath.split(/\?/)[1]);

    return <Component {...props} router={router} />;
  });
};

import { useRouter } from 'next/router';

function componentName() {
    const router = useRouter();
    console.log('router obj', router);
}

We can find the query object inside a router using which we can get all query string parameters.


If you need to retrieve a URL query from outside a component:

import router from 'next/router'

console.log(router.query)