This is the first post for the "Tips " category on this blog. Tips are intended to be short and succinct posts, proving a quick, self-contained solution to a problem.
I recently came across a weird error on one of my SvelteKit project. After returning some data from a load function, I got this weird error both in the browser and in the terminal:
I was fetching a user history from the database, so my initial thought was that I was having a database connection error or something related. Turns out, I was wrong.
After a few Google and Stack Overflow searches, I found out a few issues on the SvelteKit repository and some forums threads that put me on the right track.
That's why I was getting this error. I was returning a class instance from the load function, which is not a POJO.
The naive approach to fix this issue would be to stringify and then parse the object before returning it from the load function. This works well, and it has the advantage of a well known implementation.
Native Node.js 17+ solution
The structuredClone global has been added to Node.js versions since 17.0.0 . This function performs a deep clone of the object, which is exactly what we need in this case.
And that's it! Now you can return a non POJO object from your load function without any issues.