Sour LeangChhean
Sour LeangChhean

Reputation: 7419

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

Upvotes: 267

Views: 744779

Answers (18)

krishnaacharyaa
krishnaacharyaa

Reputation: 25080

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

Upvotes: 7

Sour LeangChhean
Sour LeangChhean

Reputation: 7419

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

Upvotes: 30

Lalit Bagga
Lalit Bagga

Reputation: 21

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 }}) => {};

Upvotes: 0

Norman Pleitez
Norman Pleitez

Reputation: 356

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

Upvotes: 1

Omar Magdy
Omar Magdy

Reputation: 3303

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

Upvotes: 91

Lonare
Lonare

Reputation: 4693

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

Upvotes: 1

junho
junho

Reputation: 3841

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

    ...
}

Upvotes: 261

Abdulrazzak Alsssouki
Abdulrazzak Alsssouki

Reputation: 319

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

Upvotes: 5

Tanmay Baid
Tanmay Baid

Reputation: 469

For client side, you can use useSearchParams

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

Upvotes: 1

electricm
electricm

Reputation: 51

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

Upvotes: 5

Bharathi Devarasu
Bharathi Devarasu

Reputation: 8327

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

Upvotes: 1

Jyoti Duhan
Jyoti Duhan

Reputation: 1094

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'] || '';

Upvotes: 4

Noodles
Noodles

Reputation: 4080

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

Upvotes: 140

han4wluc
han4wluc

Reputation: 1199

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

import router from 'next/router'

console.log(router.query)

Upvotes: 11

Mahesh Auti
Mahesh Auti

Reputation: 86

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.

Upvotes: 6

DILP
DILP

Reputation: 779

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

Upvotes: 34

Brunno Vodola Martins
Brunno Vodola Martins

Reputation: 1692

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}

Upvotes: 62

Ankur Kumar
Ankur Kumar

Reputation: 47

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

Upvotes: 1

Related Questions