How to Fix Unexpected Logout Issues in SvelteKit Caused by data-sveltekit-preload-data
Introduction
I was developing a web application using SvelteKit. Personally, I find SvelteKit to be a more enjoyable framework compared to React + Next.js due to its concise syntax.
However, I encountered an issue where the login token stored in cookies was being randomly deleted. It took me several days to figure out the cause of this problem, but I finally solved it. This blog post documents my experience.
TL;DR
・I faced an issue where hovering over the logout link caused an unintended logout.
・The root cause was the default behavior of data-sveltekit-preload-data="hover"
attribute applied to <a>
elements in SvelteKit.
・The problem was resolved by setting data-sveltekit-preload-data="off"
.
・Or using POST for logout is more idiomatically correct.
Hovering Over the Logout Link Causes Logout
The issue occurred whenever the cursor passed over the logout link. Normally, clicking the logout link removes the authentication token from cookies, logging the user out.
The culprit turned out to be SvelteKit's data-sveltekit-preload-data feature.
About data-sveltekit-preload-data
data-sveltekit-preload-data
is a Link Option feature provided by SvelteKit. By default, <a>
elements have data-sveltekit-preload-data="hover"
set, which prefetches code and, if needed, page data when a link is hovered over. This allows for fast page transitions when the link is clicked.
The possible values for this attribute are hover
and tap
, which can be changed or disabled as necessary. There are also other options like data-sveltekit-preload-code
and data-sveltekit-reload
.
What Was Happening?
The logout link had the default setting data-sveltekit-preload-data="hover"
. When hovered, a GET /logout
request was triggered (though no actual page transition occurred).
The logic to delete the token was executed within the load
function of the GET /logout
route, which caused the token to be deleted as soon as the link was hovered over.
Debugging was challenging as no logs were displayed, and it took a long time to resolve this issue.
Solution
You can prevent the hover-triggered behavior by using:<a data-sveltekit-preload-data="tap" />
or <a data-sveltekit-preload-data="off" />
.
Using POST request is more idiomatic approach for Logout because GET request should not expect any side effects.
Conclusion
If you notice processes executing at random timings, it’s a good idea to check the behavior of data-sveltekit-preload-data
.
Or GET request should expect no any side effects. Use POST request instead if the user action will effect to some sate.