Skip to content

Commit

Permalink
fix: explain why json() cannot be used in form actions (#12829)
Browse files Browse the repository at this point in the history
closes #12787

Adds a check to see if the data being returned is a Response object (such as with the helper method json()), then replies with a more helpful error message.
---------

Co-authored-by: Ben McCann <[email protected]>
  • Loading branch information
eltigerchino and benmccann authored Oct 23, 2024
1 parent 312f130 commit 723eb8b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/healthy-planets-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: better error message when a `Result` is returned from a form action
8 changes: 8 additions & 0 deletions packages/kit/src/runtime/server/page/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,14 @@ function try_deserialize(data, fn, route_id) {
// If we're here, the data could not be serialized with devalue
const error = /** @type {any} */ (e);

// if someone tries to use `json()` in their action
if (data instanceof Response) {
throw new Error(
`Data returned from action inside ${route_id} is not serializable. Form actions need to return plain objects or fail(). E.g. return { success: true } or return fail(400, { message: "invalid" });`
);
}

// if devalue could not serialize a property on the object, etc.
if ('path' in error) {
let message = `Data returned from action inside ${route_id} is not serializable: ${error.message}`;
if (error.path !== '') message += ` (data.${error.path})`;
Expand Down

0 comments on commit 723eb8b

Please sign in to comment.