Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel Vue

Preventing Flash Messages from Reappearing on Browser Back Navigation in Laravel + Vue/Inertia apps

If you're using flash messages in your Laravel + Vue/Inertia application (or any SPA really), you might have encountered this annoying issue: A user performs an action that shows a toast/flash message, navigates away, then uses the browser's back button - and suddenly the old message reappears!

This happens because modern browsers cache page states for performance reasons. When a user clicks the back button, the browser restores the entire page state from its cache, including any flash messages that were present at that time.

Understanding the Issue

Let's say you have a typical flow:

  1. User deletes a resource → Success toast appears
  2. User navigates to another page
  3. User clicks back button → The success toast unexpectedly reappears

This occurs because:

  • The browser's back/forward cache (bfcache) preserves the exact page state
  • Your flash message state is part of that cached page state
  • When restored from cache, your application can't distinguish between a fresh message and a restored one

The Solution

The key is to detect when a page is shown due to back/forward navigation. Here's a robust approach that works across different implementations:

onMounted(() => {
    // Listen for popstate events (back/forward navigation)
    window.addEventListener('popstate', () => {
        // Store information about back navigation
        sessionStorage.setItem('isBackNavigation', 'true')
    })
})

// In your flash message handling logic
const showFlashMessage = (message) => {
    // Check if we're coming from back navigation
    if (sessionStorage.getItem('isBackNavigation') === 'true') {
        // Skip showing the message
        sessionStorage.removeItem('isBackNavigation')
        return
    }

    // Show your flash message normally
    displayMessage(message)
}

Why This Works

  1. The popstate event fires when the user navigates through browser history (back/forward buttons)
  2. We use sessionStorage to persist this information across page loads
  3. The flag is checked before showing any flash messages
  4. After checking, we clear the flag to allow future flash messages to show normally

Implementation Tips

  • Use SessionStorage: Unlike localStorage, sessionStorage is cleared when the tab is closed, which is perfect for this use case
  • Clear the Flag: Always remove the flag after checking it to ensure future messages work correctly
  • Early Detection: Place the popstate listener in a component that loads early in your application lifecycle
  • Immediate Hiding: You might want to immediately hide any visible messages when back navigation is detected

Adapting to Your Setup

This solution can be adapted to various implementations:

For Toast Libraries

// Using a toast library like vue-toastification
onMounted(() => {
    window.addEventListener('popstate', () => {
        toast.dismiss() // Hide any visible toasts
        sessionStorage.setItem('isBackNavigation', 'true')
    })
})

For Flash Messages in Templates

// If you render flash messages in your template
const shouldShowFlash = computed(() => {
    return !!flashMessage.value && 
           sessionStorage.getItem('isBackNavigation') !== 'true'
})

For Server-Side Flash Messages

// In your Laravel controller
public function store()
{
    // Your logic...
    session()->flash('message', 'Success!');
    return redirect()->back();
}

// In your JavaScript
if (page.props.flash.message && !isBackNavigation()) {
    showMessage(page.props.flash.message)
}

The exact implementation might vary based on your setup, but the core concept of detecting back navigation and preventing message display remains the same.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Subscribe to my newsletter

Get new posts when I publish them.

I respect your privacy. Unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *