next.js13nextjs-dynamic-routing

Next JS router multiple accounts off query string


I have url /user/query/{ACCOUNT_NUMBER} for single account number as parameter. In NextJS, I am using useRouter and getting params from url.

How can we get multiple account numbers off query string with NextJS router.


Solution

  • What you're looking for is how Next.js handles dynamic routes.

    If your URL looks something like this: www.example.com/1/2/3 You can have access to the numbers 1, 2, and 3 by calling the useRouter hook.

    What you'll have to do is change your file name to something like this [...accountNumber].tsx

    Let's say your file is located at pages/account/[...accountNumber].tsx, when you're navigating to /account/1/2/3, Next.js will take every parameter that comes after the account/ and put it in router.query.accountNumber

            const router = useRouter()
    
            console.log(router.query.accountNumber) // ['1', '2', '3']
    

    You can read more about how Next.js handles dynamic routes here