Next.js Discord

Discord Forum

How can I use router.back( ) to redirect the user to a default url if browser history is null?

Unanswered
Cyrics posted this in #help-forum
Open in Discord
Hello. I have the following scenario:
I have created a page as a Modal with a close button. That page can be visited by either pressing on a <Link /> inside the app or by visiting directly the url of the page: localhost:3000/my_page.

If the user visits the page by the url and came from a different domain or history is null, I would like the CloseButton of the modal window which uses router.back() to redirect the user to a custom url (can be / or /about_us) instead of going to the previous website the user was.

4 Replies

you can use [history length](https://developer.mozilla.org/en-US/docs/Web/API/History/length) to determine to go back, but be aware that this method may not work well if the user came from another page
That wouldn’t work if I the user came from ie: ‘/about’, he was already on my page
but if it is adding to history, it also adds to normal browser one
I thought of a different temporary solution. I added a reduxSlicer in which I added a setting called isModal: Boolean.

Whenever I select a link inside the app, I dispatch an action which sets isModal to true.

Now the CloseButton uses that redux state and behaves accordingly