242

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>
);
Vincent J
  • 4,968
  • 4
  • 40
  • 50
Sour LeangChhean
  • 7,089
  • 6
  • 37
  • 39

16 Answers16

247

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);

    ...
}
gligoran
  • 3,267
  • 3
  • 32
  • 47
junho
  • 3,603
  • 3
  • 18
  • 25
  • 50
    router.query only works in ssr. But sometimes a url params passed to the next page but router.query cannot get this param, you have to reload this page to use rotuer.query to get his param. In this scenario, use router.asPath or window?.location.search to get the params. – MING WU Nov 15 '20 at 03:36
  • 3
    my route.query is not same as url – Ghazaleh Javaheri Feb 27 '21 at 12:16
  • 1
    Thanks @MINGWU, actually I need the info in `router.query`, it is `undefined` at the first time rendering is annoying. – Yang Dec 24 '22 at 16:55
  • For Nextjs 13 use this https://stackoverflow.com/a/76613628/13431819 – krishnaacharyaa Jul 04 '23 at 14:29
136

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}
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Noodles
  • 3,888
  • 2
  • 20
  • 31
  • 10
    if you guys want to get the query string, for example http://localhost/abc?param=1 you should change the `const {id} = router.query` variable into `const {param} = router.query`. works for me – Wisnu Wijokangko Aug 19 '21 at 02:49
  • 8
    Not sure if something changed in version 12, but I needed to check for router.isReady, otherwise router.query is an empty object – Lucas Steffen Jan 03 '22 at 14:37
62

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}

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brunno Vodola Martins
  • 1,582
  • 2
  • 15
  • 17
38

In the New NextJS 13, there are two main ways that this can be done:

1) Server Components:

export default function Home({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  const pageNumber= searchParams["p"] ?? "1"; // default value is "1"

  return (<>Current page is: {pageNumber}</>);
}

Reference: https://nextjs.org/docs/app/api-reference/file-conventions/page

2) Client Components:

'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function Home() {
  const searchParams = useSearchParams()
 
  const pageNumber= searchParams.get('p') ?? "1"; // default value is "1"
 
  return <>Current Page is : {pageNumber}</>
}

Reference: https://nextjs.org/docs/app/api-reference/functions/use-search-params

Omar Magdy
  • 2,331
  • 14
  • 13
33

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} />;
  });
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DILP
  • 759
  • 9
  • 14
29
  • Get it by using the below code in the about.js page:

    Enter image description here

// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
  <p>Welcome to About! { name }</p>
)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sour LeangChhean
  • 7,089
  • 6
  • 37
  • 39
11

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

import router from 'next/router'

console.log(router.query)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
han4wluc
  • 1,179
  • 1
  • 14
  • 26
5
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahesh Auti
  • 76
  • 1
  • 3
5

What worked for me in Nextjs 13 pages in the app directory (SSR)

Pass params and searchParams to the page:

export default function SomePage(params, searchParams) { 
console.log(params);
console.log(searchParams);

return <div>Hello, Next.js!</div>;

With some builds there may be a bug that can be solved by adding: export const dynamic='force-dynamic'; especially when deploying on Vercel.

ref: https://beta.nextjs.org/docs/api-reference/file-conventions/page#searchparams-optional
https://github.com/vercel/next.js/issues/43077

electricm
  • 51
  • 1
  • 1
5

In Nextjs 13.4 You can use useParams and useSearchParams.

  1. params - UseParams()
'use client'
 
import { useParams } from 'next/navigation'
 
export default function ExampleClientComponent() {
  const params = useParams()
 
  // Route -> /shop/[tag]/[item]
  // URL -> /shop/shoes/nike-air-max-97
  // `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
  console.log(params)
 
  return <></>
}
  1. searchParams - useSearchParams()
'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function SearchBar() {
  const searchParams = useSearchParams()
 
  const search = searchParams.get('search')
 
  // URL -> `/dashboard?search=my-project`
  // `search` -> 'my-project'
  return <>Search: {search}</>
}

Also refer latest Nextjs 13 code templates Next.js 13+ Power Snippets | TypeScript/Javascript

It includes wide range of code snippets for both ts and js. Find all snippets here


krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
4

Using {useRouter} from "next/router"; helps but sometimes you won't get the values instead u get the param name itself as value. This issue happens when u are trying to access query params via de-structuring like:

let { categoryId = "", sellerId = "" } = router.query;

and the solution that worked for me is try to access the value directly from query object:

let categoryId  = router.query['categoryId'] || '';
let sellerId  = router.query['sellerId'] || '';
Jyoti Duhan
  • 988
  • 1
  • 16
  • 26
4

For anyone who is looking for an answer realted to Next.js 13 using App router:

In Server Side, you get the query automaticly `

const exmaple = (searchParams) => {
    console.log(searchParams.query) //Depend on your query name
  }
  export default example;

` In Client Side, you use useSearchParams hook, more in the docs link: Go here

1

Post.getInitialProps = async function(context) {

  const data = {}
  try{
    data.queryParam = queryString.parse(context.req.url.split('?')[1]);
  }catch(err){
    data.queryParam = queryString.parse(window.location.search);
  }
  return { data };
};
1
import { useRouter } from 'next/router'

const Home = () => {

  const router = useRouter();

  const {param} = router.query

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

Also you can use getInitialProps, more details refer the below tutorial.

get params from url in nextjs

Bharathi Devarasu
  • 7,759
  • 2
  • 18
  • 23
1

For client side, you can use useSearchParams

See: https://nextjs.org/docs/app/api-reference/functions/use-search-params

Tanmay Baid
  • 459
  • 4
  • 19
1

For next js 13.x.x it has been changed to a new way:

first import

import { useParams, useRouter, useSearchParams, usePathname } from 'next/navigation';

Then use:

const params                          = useParams()
const id                              = params.id; 

You can also use usePathname for previous asPath parameters:

 const asPath                        = usePathname();
Lonare
  • 3,581
  • 1
  • 41
  • 45