How to get URL query string on Next.js static site generation?

Viewed 13545

I want to get query string from URL on Next.js static site generation.

I found a solution on SSR but I need one for SSG.

Thanks

enter image description here

3 Answers

import { useRouter } from "next/router";
import { useEffect } from "react";

const router = useRouter();

useEffect(() => {
    if(!router.isReady) return;
    const query = router.query;
  }, [router.isReady, router.query]);

It works.

I actually found a way of doing this

const router = useRouter()

useEffect(() => {
    const params = router.query
    console.log(params)
}, [router.query])

You don't have access to query params in getStaticProps since that's only run at build-time on the server.

However, you can use router.query in your page component to retrieve query params passed in the URL on the client-side.

// pages/shop.js

import { useRouter } from 'next/router'

const ShopPage = () => {
    const router = useRouter()
    console.log(router.query) // returns query params object

    return (
        <div>Shop Page</div>
    )
}

export default ShopPage

If a page does not have data fetching methods, router.query will be an empty object on the page's first load, when the page gets pre-generated on the server.

From the next/router documentation:

query: Object - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have data fetching requirements. Defaults to {}

As @zg10 mentioned in his answer, you can solve this by using the router.isReady property in a useEffect's dependencies array.

From the next/router object documentation:

isReady: boolean - Whether the router fields are updated client-side and ready for use. Should only be used inside of useEffect methods and not for conditionally rendering on the server.

Related