0

with nextjs I am facing an. issue with the router back() function.

The issue: is if the user enters the page with an url and clicks the back button, then he will be put back to a previews page. So if I was in, example, youtube.com than in url enter my website address and inside i click back - i will be put back to youutbe.com.

What I need: if the user entered the page from some other webiste - the back button should redirect to home page /. But if he entered the page while within my page (example in home page clicked /posts) then he should be redirected back to the previews page he was on.

I tried using document.referrer but its always empty...

  • Does [this](https://stackoverflow.com/questions/55565631/how-to-get-previous-url-in-next-js) help answer your question? You can run it conditionally based on the result with `startsWith()` for example. – Luke Mar 08 '23 at 16:09
  • server side props. thats right! I forgot that such data is on the server not client. Yes this solves my issue, thx – Edvinas Baranauskas Mar 08 '23 at 16:26
  • Great, I've answered the question. Please tick it to say your question has been answered. – Luke Mar 08 '23 at 16:30

1 Answers1

0

You find the Referer ( so the previous URL ) in the context of getServerSideProps or any other Data fetching methods

as

context.req.headers.referer  

example in code

export async function getServerSideProps(context) {
  console.log(context.req.headers.referer)
}

You can then use conditional logic, for example .startsWith() to determine where you would like to send the user, possibly by setting the state on the first render with useEffect().

Luke
  • 761
  • 1
  • 18