267

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

However, when I'm passing a parameter name through the 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>
);
2

18 Answers 18

261

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

    ...
}
Sign up to request clarification or add additional context in comments.

5 Comments

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.
my route.query is not same as url
Thanks @MINGWU, actually I need the info in router.query, it is undefined at the first time rendering is annoying.
The query object has been removed and is replaced by useSearchParams() nextjs.org/docs/app/api-reference/functions/…
140

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}
}

2 Comments

if you guys want to get the query string, for example localhost/abc?param=1 you should change the const {id} = router.query variable into const {param} = router.query. works for me
Not sure if something changed in version 12, but I needed to check for router.isReady, otherwise router.query is an empty object
92

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

2 Comments

This should be the accepted answer! Just a comment, you can type searchParams as { searchParams?: { query?: string } }
Note that in NextJS 15 searchparams are a promise in server components
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}

4 Comments

Is it possible to prevent refresh. I just want the url to update without a refresh
In the Hooks era, go for the useRouter solution, it's much cleaner than getInitialProps
How to add multiple values for a single param? ex. a=1,2,3
@sanjeevshetty, if you pass your a param like so, you could get it in query.a as a string, "1,2,3", and then do query.a.split(',') to have ["1", "2", "3"].
34

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

Comments

30

Get it by using the below code in the about.js page:

// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
  <p>Welcome to About! { name }</p>
)

3 Comments

:) We also can use another way too.
@DanielKmak yes
This approach currently throws a warning: the 'url' property is deprecated. err.sh/zeit/next.js/url-deprecated Juneho Nam's answer should be the accepted one: stackoverflow.com/a/57389355/4642023
11

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

import router from 'next/router'

console.log(router.query)

1 Comment

You should only use "next/router" on the client side of your app.
8

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}</>
}

Comments

6
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.

Comments

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

Comments

5

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

2 Comments

it would be nice if you also could add the server-side link documentation
There is a docs about that for server side but only when using page route, you can check it in the bottom of page following the same link I provided
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'] || '';

Comments

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 Comment

query can be accessed directly from getInitialProps using context.req.query.
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

Comments

1

For client side, you can use useSearchParams

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

Comments

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

Comments

1

It looks like you are already passing the parameters right, so you can use useSearchParams.

'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function AboutUs() {
  const searchParams = useSearchParams()
 
  const nameFromIndex = searchParams.get('name')
 
  // URL -> '/about?name=leangchhean'
  return <>Show this: {nameFromIndex}</>
}

Comments

0

For server side in TS you can use like. where paramKey will be the key of parameter you have sent from another screen

const ExamplePage = async ({ searchParams }: { searchParams: { paramKey:string }}) => {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.