CSRF Tokens: Preventing Onboarding Tour Issues
When building interactive tours, ensure all API requests include CSRF tokens to prevent unexpected failures. Let's look at a recent fix in Reimpact/platform, a project focused on modernizing user interaction flows. The team addressed an issue where the onboarding tour restarted on every page load.
The Problem: Missing CSRF Tokens
The tour's JavaScript fetch calls lacked the X-CSRF-TOKEN header. Laravel, the backend framework, rejected the POST request to the /complete endpoint with a 419 error. This prevented the onboarding_completed_at flag from being saved, causing the tour to restart continuously.
The Solution: Adding the Missing Header
To resolve this, the team added the X-CSRF-TOKEN header to the API requests made by the onboarding tour. Here's a basic example of how to include the token in a fetch request:
fetch('/complete', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
})
Key Takeaway
Always include CSRF tokens in your application's API requests, especially those modifying data. This prevents common server-side validation errors. Check the full article for a more detailed look.