Using nextjs with next-routes, is it possible to preserve the URL's query string when navigating between pages? I have an ad-campaign running and I need to preserve it as I navigate through pages for historic reasons and tracking.
I cannot stuff this into a Redux store, or localhost, sessionstorage, etc. It must remain in the URL.
I tried something like the following:
import { Router } from 'routes';
Router.events.on('routeChangeStart', (url: string) => {
if (Router.query && Router.router.pathname !== url) {
const href = `${url}${Object.keys(Router.query).reduce(
(carry: string, key: string) => {
carry += `${carry === '' ? '?' : '&'}${key}=${Router.query[key]}`;
return carry;
},'')}`;
Router.pushRoute(href, Router.router.pathname, { shallow: true });
}
});
And the routes.js file exports next-routes:
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
What happens here is that the URL is correctly pushed and the query string persists, but only for a momentary flash. It immediately pushes the original url back into the Router and I lose my query string arguments.
I've tried several other variations but unfortunately I cannot find the correct implementation.
Any help is appreciated.
routeChangeStartevent detects) you can do some actions, but not change the route itself, which is probably why you see that brief flash before it reverts back to the original route being requested. You should consider maybe defining your ownLinkWithQuerycomponent that wraps next's Link component and appends the querystring you want to preserve to any such Link.