Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
NextJs <Link> wont trigger beforeunload event. Trying to prompt user before leaving page

Im trying to prompt user before leaving page. I Noticed when user enters page from a element link then when I click back, beforeunload event fires.

However, when user enters page through NextJs Link component then clicking back wont fire beforeunload event.

How can I still prompt user when using component?

for example going tho page through this Link and clicking back wont trigger beforeunload

<Link href={`/event/${encodeURIComponent(event.slug)}`}>
      <a>
        <h3>{event.name}</h3>
      </a>
</Link>

but regular a element linking will then afterwards fire beforeunload when clicking back

example

<a href={"event/" + event.slug}>
      <h3>{event.name}</h3>
</a>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

According to the Next.js documentation, when you are using the Link component:

Client-side transitions between routes can be enabled via the Link component exported by next/link. The Next.js router allows you to do client-side route transitions between pages, similar to a single-page application.

You are using the Link component to change your routes, so it's considered you are on a single page (even go back and forward many times).

Now, take a look at Window: beforeunload event on MDN:

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

So, as you use the Link component with mentioned specific, it't a proper behavior.

As a solution to solve the issues, you can add useEffect hook and do the proper action on it or on the cleanup method. for example, put your function in the useEffect on the desired page to get called on component did mount. in this way, with every change on the routes or pages, the useEffect will be triggered.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!