Search code examples
next.jsquery-stringnext.js13app-router

NextJS app router - get all query parameters in string


I thought this would be easy but I am struggling greatly. I have a page with multiple query params:

/pathname?param1=lorem&param2=ipsum&param3=dolor&param4=sit

All I want is to be able to use this string in my component:

param1=lorem&param2=ipsum&param3=dolor&param4=sit

How to do this?


Solution

  • If you're on the client you can typically use the useSearchParms hook from next/navigation.

    If you're on the backend you can use the request object.

    Here are some examples:

    Client

    The client has a hook provided by Next.js. Read the docs here.

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

    The code above is directly from the documentation.

    You should consult the request object docs via MDN for details on using that directly, e.g. req.url.

    Backend

    For the full string use the url and/or pull the request parameters from that url using .get.

    import { NextRequest } from 'next/server'
    
    export async function GET(req: NextRequest) {
        const reqUrl = req.url
        const { searchParams } = new URL(reqUrl)
        console.log(searchParams.get("param1")) // should print lorem
    }