Skip to content

Commit 939188e

Browse files
authored
Include charset=utf-8 by default in application/json endpoints. (#1669)
1 parent c639586 commit 939188e

File tree

5 files changed

+23
-3
lines changed

5 files changed

+23
-3
lines changed

.changeset/fuzzy-kids-turn.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/kit': patch
3+
---
4+
5+
Use UTF-8 encoding for JSON endpoint responses by default

packages/kit/src/runtime/server/endpoint.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,11 @@ export default async function render_route(request, route) {
5454
/** @type {import('types/hooks').StrictBody} */
5555
let normalized_body;
5656

57-
if (typeof body === 'object' && (!type || type === 'application/json')) {
58-
headers = { ...headers, 'content-type': 'application/json' };
57+
if (
58+
typeof body === 'object' &&
59+
(!type || type === 'application/json' || type === 'application/json; charset=utf-8')
60+
) {
61+
headers = { ...headers, 'content-type': 'application/json; charset=utf-8' };
5962
normalized_body = JSON.stringify(body);
6063
} else {
6164
normalized_body = /** @type {import('types/hooks').StrictBody} */ (body);

packages/kit/test/apps/basics/src/routes/encoded/_tests.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,9 @@ export default function (test) {
2727
assert.equal(await page.innerHTML('h2'), '/encoded/苗条');
2828
assert.equal(await page.innerHTML('h3'), '/encoded/苗条');
2929
});
30+
31+
test('sets charset on JSON Content-Type', null, async ({ fetch }) => {
32+
const response = await fetch('/encoded/endpoint');
33+
assert.equal(response.headers.get('content-type'), 'application/json; charset=utf-8');
34+
});
3035
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export async function get() {
2+
return {
3+
body: {
4+
fruit: '🍎🍇🍌'
5+
}
6+
};
7+
}

packages/kit/test/apps/basics/src/routes/load/_tests.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export default function (test, is_dev) {
1414
});
1515

1616
const payload =
17-
'{"status":200,"statusText":"","headers":{"content-type":"application/json"},"body":"{\\"answer\\":42}"}';
17+
'{"status":200,"statusText":"","headers":{"content-type":"application/json; charset=utf-8"},"body":"{\\"answer\\":42}"}';
1818

1919
if (!js) {
2020
// by the time JS has run, hydration will have nuked these scripts

0 commit comments

Comments
 (0)