When using Next.js (which I assume you meant by "nuqs") and navigating to other pages, the URL query string (i.e., the part of the URL that comes after the ?) is not persisted by default. This is because Next.js uses client-side routing, which doesn't automatically preserve the query string when navigating to a new page.
To persist the query string when navigating to other pages, you can use one of the following approaches:
1. Using next/link with as prop
When using next/link, you can pass the as prop to specify the URL that will be displayed in the browser. You can include the query string in the as prop to persist it:
import Link from 'next/link';
const MyLink = () => {
const query = { foo: 'bar' };
const href = {
pathname: '/new-page',
query,
};
const as = {
pathname: '/new-page',
query,
};
return (
<Link href={href} as={as}>
<a>Go to new page</a>
</Link>
);
};
In this example, when you click on the link, the query string ?foo=bar will be preserved.
2. Using router.push with query option
When using the router object from next/router, you can pass the query option to push to specify the query string:
import { useRouter } from 'next/router';
const MyComponent = () => {
const router = useRouter();
const handleClick = () => {
router.push({
pathname: '/new-page',
query: { foo: 'bar' },
});
};
return (
<div>
<button onClick={handleClick}>Go to new page</button>
</div>
);
};
In this example, when you click on the button, the query string ?foo=bar will be preserved.
3. Using a custom withQuery Higher-Order Component (HOC)
You can create a custom HOC that wraps your page components and persists the query string:
import { withRouter } from 'next/router';
const withQuery = (WrappedComponent) => {
const EnhancedComponent = ({ router, ...props }) => {
const query = router.query;
const pathname = router.pathname;
const handleRouteChange = (newPathname, newQuery) => {
router.push({ pathname: newPathname, query: { ...query, ...newQuery } });
};
return (
<WrappedComponent
{...props}
router={{ ...router, query, pathname, handleRouteChange }}
/>
);
};
return withRouter(EnhancedComponent);
};
export default withQuery;
You can then wrap your page components with this HOC to persist the query string.
Choose the approach that best fits your use case!