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...
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()
.