1

I need to get the previous url in a nextjs project. I found this but it doesn't help because it always prints me the base url (http://localhost:3000/) with this method (document.referrer). I also tried to push a state into window.history based on official developer mozilla doc.

In the last case I click on a link and it redirects me to another page. On this page I need to know where I come from. I tried:

//pathname is a string containing the actual pathname
history.pushState({prevPath: pathname},pathname)

If I print history in the new page then I don't see any prevState in the state field.

Loudrous
  • 1,039
  • 10
  • 29
  • history.pushState({foo:bar},'title',pathname) ? – bZezzz Nov 07 '21 at 16:33
  • The last parameter is optional. I tried in this way also but nothing changes.. I always get this: state: { "url": "/search?keyword=tag1", "as": "/search?keyword=tag1", "options": { "scroll": true }, "__N": true, "idx": 23 } **state** is the state of history – Loudrous Nov 07 '21 at 16:40
  • ANd with history.replaceState(stateObj, "page 3", "bar2.html"); ? No trace ? – bZezzz Nov 07 '21 at 16:46
  • Does this answer your question: [How to get history and match in this.props in nextjs?](https://stackoverflow.com/a/65614253/1870780)? Check out the `useRouteUrlHistory` hook implementation in the top answer. – juliomalves Nov 07 '21 at 18:21

1 Answers1

0

You can simply create a state which is an object that has two properties: previousUrl and currentUrl like this:

const urlReducer = (state={previousUrl: null, currentURL: null},action) => {
    switch(action.type){
        case "SET_URLS":
            return {previousUrl: state.currentUrl, currentUrl: window.location.href}
        default:
            return state;
    }
}

Then all you need to do is dispatch an action in every page you visit like this:

const dispatch = useDispatch();

useEffect(()=>{
    dispatch({type: "SET_URLS"});
},[]);
noiseymur
  • 761
  • 2
  • 15