6

I have a news page in a Next.js site at the URL /news

On the page are some category buttons. Clicking these makes an API request and dynamically changes the posts listed on the page.

What I want is for the URL to reflect these filters, for example /news/category/entertainment and /news/category/technology

I see 2 options for this, and both have issues.

Option 1:

I use Next.js router, for example:

router.replace(updatedUrl, undefined, { shallow: true });

However, this causes the page to reload every time I change category, which must not happen.

Option 2:

I use the history API, for example:

window.history.replaceState(null, null, updatedUrl);

This works almost perfectly, but it breaks the browser back and forward buttons. They correctly take you away to other pages, but if the browser buttons navigate back to the /news page then Next.js just does nothing and stays on the previous page. Browser history API is obviously incompatible with Next.js router.

Question:

Is there a solution to append my categories to my /news URL without Next.js reloading the page, and ensuring the browser back and forwards buttons work? I do not want to use query parameters. I am concluding that it must be impossible, but hoping someone can help.

One of those annoying things that I would know exactly how to do with vanilla js, but I’m stuck fighting a framework that seemingly doesn’t want me to do this.

Thanks

2
  • Wondering if I can use history API and add a history popstate listener, then force Next.js to load the pages that the browser buttons are ignoring. But it seems Next.js already uses this, and I cant see a way to detect whether or not Next.js will handle or ignore history events.
    – Alex
    Commented Oct 19, 2023 at 12:16
  • Maybe use router.push method. [link](nextjs.org/docs/pages/api-reference/functions/use-router )
    – BugHunter
    Commented Oct 19, 2023 at 12:37

1 Answer 1

1

Check out this solution.If you pass {} instead of window.history.state, moving forward/back will potentially be broken. https://github.com/vercel/next.js/discussions/18072

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.