New SvelteKit course: fullstacksveltekit.com

Fix the 'Cannot stringify arbitrary non-POJOs' error in SvelteKit

Justin's profile pic

Justin Ahinon

Last updated on

Enter your email to get this article emailed to you

SvelteKit version: 1.3.1

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.

Some background

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:

Error in the browser Error in the console

code loading...

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.

The issue

SvelteKit load function expect to return Plain Old JavaScript Objects (POJOs ). This means that you can't return a class instance or a function. You can only return a plain object. Some libraries, such as Pocketbase JavaScript SDK (which I was using), can return a class instance on some methods.

That's why I was getting this error. I was returning a class instance from the load function, which is not a POJO.

The solution

Naive approach

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.

code loading...

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.

code loading...

And that's it! Now you can return a non POJO object from your load function without any issues.

You might also like these blog posts

A lovely bath

Discover how SvelteKit's load function simplifies data loading in your web app.

A lovely bath

Master the art of query parameters in SvelteKit! Discover how to access and use them on both the client and server side with clear examples and explanations.