Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fluffy-fans-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Only serialize data once body is rendered
50 changes: 25 additions & 25 deletions packages/kit/src/runtime/server/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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 }) => `<script type="svelte-data" url="${url}">${payload}</script>`)
.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<script type="svelte-data" url="${url}">${payload}</script>`;
}
}

/** @type {import('types.internal').Headers} */
const headers = {
Expand Down