Skip to main content

How to use params and searchParams in Nextjs 13

There are 3 different variants of params

  1. params (/blog/1)
    • single params
    • multiple params
  2. searchParams (/blog?postId=123)
    • single search params
    • multiple search params
  3. Both params and searchParams (/blog/1?postId=123)

There are multiple ways to handle this

  1. For 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. For 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}</>
}
  1. Both params and search Params using any type
'use client'

export default function BlogPost(props: any) {

    // URL -> blog/a/b?param1=IamfirstParam&param2=IamsecondParam
    return <div>{props}</div>;

   // Output ->
   //{
   //  params: { blogId: [ 'a', 'b' ] },
   //  searchParams: { param1: 'IamfirstParam', param2: 'IamsecondParam' }
   //}
}
  1. Both params and search Params using defined type
'use client';

// URL -> blog/a/b?param1=IamfirstParam&param2=IamsecondParam

export default function BlogPost({
    params,
    searchParams,
}: {
    params: { blogId: string[] };
    searchParams: { param1: string; param2: string };
}) {


    return (
        <div>
            {params.blogId[0]}
            {params.blogId[1]}
            {searchParams.param1}
            {searchParams.param2}
        </div>
    );
}

Server Components 

In order to get params and searchParams in server side component using typescript in Next.js 13, you should define what params and searchParams do you expect. For example:

// /app/category/[slug]/page.tsx
// Request URL localhost:3000/category/news?page=2

export default function PostsCategory({ params, searchParams }: { params: { slug: string }; searchParams: { page: string } }) {
  const posts = getPostsByTag(params.slug, ['title', 'date', 'excerpt', 'image', 'slug', 'tags']);
  const currentPage = searchParams && searchParams.page ? Number(searchParams.page) : 1;
  const { slug } = params;

  return (
    <main>
      <PaginatedPosts posts={posts} page={currentPage} title={`${slug}`} />
    </main>
  );
}