Skip to content

Retrieve previous route and/or route history in Next router #36723

Answered by icyJoseph
michaeljblum asked this question in Help
Discussion options

You must be logged in to vote

I think this is a tricky one...

Generally, all routing solutions, use the history API, and that has its ups and downs. You can see in the browser yourself, window.history prints a few properties.

Routing solutions take care of a bunch of things for you, but the idea of giving access to the history stack is terrifying, because, it is highly mutable (replace for example).

That being said, I can think of a couple of approaches:

// this would have to go in `_app.tsx` to be a true previous route tracker (across all pages)
const usePreviousRoute = () => {
  const { asPath } = useRouter();

  const ref = useRef<string | null>(null);

  useEffect(() => {
    ref.current = asPath;
  }, [asPath]);

  

Replies: 7 comments 16 replies

Comment options

You must be logged in to vote
10 replies
@cglacet
Comment options

@kasir-barati
Comment options

@Stillonov
Comment options

@cglacet
Comment options

@AhmedMuhammedElsaid
Comment options

Answer selected by michaeljblum
Comment options

You must be logged in to vote
2 replies
@david-vendel
Comment options

@david-vendel
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@asouthern729
Comment options

@janvorwerk
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@Malin88
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet