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