Warn Users Before They Lose Unsaved Changes in Nuxt

One composable that covers in-app links, the back button, reloads, and closing the tab, without nagging users who already saved

Someone spends ten minutes on a settings form, clicks a link in the sidebar, and everything they entered is gone. A "you have unsaved changes" warning prevents that, but most examples online only handle half the problem. A user can leave a page in two very different ways:

  • Inside your app: clicking a link, calling navigateTo(), or pressing the browser's back button. Vue Router handles these, so a route guard can stop them.
  • Leaving the page entirely: closing the tab, reloading, or typing a new URL. The router never sees these. Only the browser's beforeunload event can.

A reliable guard needs both, and it needs to stay quiet once the user has saved.

The composable

      
// composables/useUnsavedChanges.ts
import { onBeforeUnmount, onMounted, toValue, watch, type MaybeRefOrGetter } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'

export function useUnsavedChanges(
  isDirty: MaybeRefOrGetter<boolean>,
  confirmLeave: () => boolean | Promise<boolean> = () =>
    window.confirm('You have unsaved changes. Leave this page anyway?')
) {
  // 1. In-app navigation: links, navigateTo(), back/forward buttons
  onBeforeRouteLeave(async () => {
    if (!toValue(isDirty)) return true
    return await confirmLeave()
  })

  // 2. Closing the tab, reloading, or leaving the site
  const onBeforeUnload = (event: BeforeUnloadEvent) => {
    event.preventDefault()
    event.returnValue = '' // older Chrome and Edge need this too
  }

  // Only listen while there are unsaved changes
  onMounted(() => {
    watch(() => toValue(isDirty), (dirty) => {
      if (dirty) window.addEventListener('beforeunload', onBeforeUnload)
      else window.removeEventListener('beforeunload', onBeforeUnload)
    }, { immediate: true })
  })

  onBeforeUnmount(() => window.removeEventListener('beforeunload', onBeforeUnload))
}

Returning false from onBeforeRouteLeave cancels the navigation, and the guard can be async, so confirmLeave can return a promise. The beforeunload listener is added only while the form is dirty: a permanent listener can stop the browser from using its back/forward cache, which makes the back button slower on every page that uses it. The watcher starts in onMounted because window doesn't exist during server rendering.

Knowing when the form is dirty

The simplest reliable check is to compare the form to a snapshot of what was last saved:

      
const form = reactive({ name: '', email: '', notifications: true })

const saved = ref(JSON.stringify(form))
const isDirty = computed(() => JSON.stringify(form) !== saved.value)

async function save() {
  await $fetch('/api/settings', { method: 'PUT', body: form })
  saved.value = JSON.stringify(form)   // mark clean *before* navigating
  await navigateTo('/dashboard')
}

useUnsavedChanges(isDirty)

Comparing against a snapshot, instead of flipping a flag on every input, means that typing something and then deleting it counts as clean again. If the form loads its data asynchronously, update saved once the data arrives, or the form will look dirty before the user has touched it.

Using your own dialog

window.confirm works, but it's unstyled and blocks the page. Because the guard awaits confirmLeave, any modal that returns a promise can replace it:

      
useUnsavedChanges(isDirty, () =>
  openConfirmDialog({            // your modal, resolving to true or false
    title: 'Discard changes?',
    message: "Your changes to this page haven't been saved.",
    confirmText: 'Discard',
    cancelText: 'Keep editing'
  })
)

Name the buttons after what they do. "Discard" and "Keep editing" are clearer than "OK" and "Cancel", where it's never obvious which one loses the work.

Gotchas

  • Browsers ignore your beforeunload message. Modern browsers always show their own generic "Leave site?" dialog when the tab closes or reloads. Only in-app navigation can use your wording or your modal.
  • No dialog without interaction. Browsers only show the beforeunload dialog if the user has interacted with the page. In practice that's fine: if they haven't typed anything, there's nothing to lose.
  • Reset the snapshot before you navigate. If save() calls navigateTo() before updating saved, your own guard asks the user whether they want to lose the changes they just saved.
  • Same-route changes aren't covered. Going from /settings?tab=profile to /settings?tab=billing reuses the same page component, so onBeforeRouteLeave doesn't run. Use onBeforeRouteUpdate with the same check if your tabs are query parameters.
  • Call it from a page, or a component inside one. onBeforeRouteLeave only works in components rendered by <NuxtPage>. It won't fire from a layout or app.vue.

Lessons learned

  • Cover both exits. A route guard alone misses reloads and closed tabs; beforeunload alone misses every in-app link.
  • Track dirty state by comparison. A snapshot of the last save is simpler and more accurate than tracking every edit.
  • Only listen when it matters. Adding beforeunload only while the form is dirty keeps the rest of the app fast.
  • Never warn about work that's already saved. A guard that fires after a successful save teaches users to click through it without reading.

Conclusion

About 30 lines of composable protect every form in an app from the most frustrating kind of data loss. Drop useUnsavedChanges(isDirty) into any page with a form, and users get a warning exactly when they need one and never when they don't.

Let me know if you found this useful. Feel free to reach out to me with any questions on LinkedIn.