How can I get (query string) parameters from the URL in Next.js?
Asked Answered
M

18

261

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>
);
Monochromatic answered 9/5, 2017 at 6:28 Comment(2)
For Nextjs 13 use this https://mcmap.net/q/111107/-get-url-params-next-js-13Gradualism
Related: Get URL Params (Next.js 13)Chafe
M
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>
)
Monochromatic answered 9/5, 2017 at 6:28 Comment(3)
:) We also can use another way too.Hepza
@DanielKmak yesMonochromatic
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: https://mcmap.net/q/109115/-how-can-i-get-query-string-parameters-from-the-url-in-next-jsGizela
T
255

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

    ...
}
Torbert answered 7/8, 2019 at 7:45 Comment(5)
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.Shut
my route.query is not same as urlBlocking
Thanks @MINGWU, actually I need the info in router.query, it is undefined at the first time rendering is annoying.Garzon
For Nextjs 13 use this https://mcmap.net/q/111107/-get-url-params-next-js-13Gradualism
The query object has been removed and is replaced by useSearchParams() nextjs.org/docs/app/api-reference/functions/…Statued
D
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}
}
Dump answered 23/5, 2020 at 8:35 Comment(2)
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 mePlaty
Not sure if something changed in version 12, but I needed to check for router.isReady, otherwise router.query is an empty objectCarlenecarleton
K
71

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

Kumamoto answered 17/2, 2022 at 9:38 Comment(2)
Works like a magic. Thanks!Riccio
This should be the accepted answer! Just a comment, you can type searchParams as { searchParams?: { query?: string } }Nabalas
S
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}

Sawyers answered 16/10, 2018 at 15:19 Comment(4)
Is it possible to prevent refresh. I just want the url to update without a refreshRahr
In the Hooks era, go for the useRouter solution, it's much cleaner than getInitialPropsPigweed
How to add multiple values for a single param? ex. a=1,2,3Mitzi
@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"].Sawyers
U
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} />;
  });
};
Utterance answered 20/6, 2019 at 23:47 Comment(0)
M
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>
)
Monochromatic answered 9/5, 2017 at 6:28 Comment(3)
:) We also can use another way too.Hepza
@DanielKmak yesMonochromatic
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: https://mcmap.net/q/109115/-how-can-i-get-query-string-parameters-from-the-url-in-next-jsGizela
L
11

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

import router from 'next/router'

console.log(router.query)

Lalo answered 30/3, 2020 at 4:57 Comment(1)
You should only use "next/router" on the client side of your app.Elf
G
7

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


Gradualism answered 11/7, 2023 at 9:23 Comment(0)
D
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.

Dry answered 19/2, 2020 at 13:10 Comment(0)
F
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

Feuchtwanger answered 15/2, 2023 at 21:45 Comment(0)
A
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

Ataractic answered 18/5, 2023 at 15:14 Comment(2)
it would be nice if you also could add the server-side link documentationJangro
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 providedAtaractic
D
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'] || '';
Danu answered 25/2, 2022 at 6:55 Comment(0)
L
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 };
};
Landlordism answered 30/1, 2020 at 15:6 Comment(1)
query can be accessed directly from getInitialProps using context.req.query.Monocular
T
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

Templetempler answered 16/1, 2023 at 9:5 Comment(0)
S
1

For client side, you can use useSearchParams

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

Szombathely answered 16/5, 2023 at 20:53 Comment(0)
R
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();
Raama answered 7/7, 2023 at 10:28 Comment(0)
C
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}</>
}

Corker answered 29/1 at 17:0 Comment(0)
F
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 }}) => {};
Fishnet answered 11/4 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.