diff --git a/.changeset/fluffy-fans-watch.md b/.changeset/fluffy-fans-watch.md
new file mode 100644
index 000000000000..30c0a3723451
--- /dev/null
+++ b/.changeset/fluffy-fans-watch.md
@@ -0,0 +1,5 @@
+---
+'@sveltejs/kit': patch
+---
+
+Only serialize data once body is rendered
diff --git a/packages/kit/src/runtime/server/page.js b/packages/kit/src/runtime/server/page.js
index e832e49b032f..89c709dc91be 100644
--- a/packages/kit/src/runtime/server/page.js
+++ b/packages/kit/src/runtime/server/page.js
@@ -26,8 +26,8 @@ async function get_response({ request, options, $session, route, status = 200, e
throw new Error(`Failed to serialize session data: ${error.message}`);
});
- /** @type {Array<{ url: string, payload: string }>} */
- const serialized_data = [];
+ /** @type {Array<{ url: string, response: Response }>} */
+ const inline_data = [];
const match = route && route.pattern.exec(request.path);
const params = route && route.params(match);
@@ -126,24 +126,11 @@ async function get_response({ request, options, $session, route, status = 200, e
}
if (response) {
- const clone = response.clone();
-
- /** @type {import('types.internal').Headers} */
- const headers = {};
- clone.headers.forEach((value, key) => {
- if (key !== 'etag') headers[key] = value;
+ inline_data.push({
+ url,
+ response: response.clone()
});
- const payload = JSON.stringify({
- status: clone.status,
- statusText: clone.statusText,
- headers,
- body: await clone.text() // TODO handle binary data
- });
-
- // TODO i guess we need to sanitize/escape this... somehow?
- serialized_data.push({ url, payload });
-
return response;
}
@@ -353,14 +340,27 @@ async function get_response({ request, options, $session, route, status = 200, e
init
].join('\n\n');
- const body = options.amp
- ? rendered.html
- : `${rendered.html}
+ let body = rendered.html;
+
+ if (!options.amp) {
+ for (const { url, response } of inline_data) {
+ /** @type {import('types.internal').Headers} */
+ const headers = {};
+ response.headers.forEach((value, key) => {
+ if (key !== 'etag') headers[key] = value;
+ });
- ${serialized_data
- .map(({ url, payload }) => ``)
- .join('\n\n\t\t\t')}
- `.replace(/^\t{2}/gm, '');
+ const payload = JSON.stringify({
+ status: response.status,
+ statusText: response.statusText,
+ headers,
+ body: await response.text() // TODO handle binary data
+ });
+
+ // TODO i guess we need to sanitize/escape this... somehow?
+ body += `\n\n\t`;
+ }
+ }
/** @type {import('types.internal').Headers} */
const headers = {