π Prefer Response.json() over new Response(JSON.stringify()).
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§ This rule is automatically fixable by the --fix CLI option.
Response.json() is a cleaner and more explicit way to create JSON responses. It automatically stringifies the data and sets the correct Content-Type header to application/json, whereas manually using JSON.stringify() requires you to handle the content-type yourself.
The autofix is skipped when the data is undefined, void β¦, a function, or a class, including TypeScript assertions around them. JSON.stringify() returns undefined for these, while Response.json() throws.
// β
const response = new Response(JSON.stringify(data));
// β
const response = Response.json(data);// β
const response = new Response(JSON.stringify(users), {
headers: {'Content-Type': 'application/json'},
});
// β
const response = Response.json(users);// β
const response = new Response(JSON.stringify({error: 'Not found'}), {
status: 404,
headers: {'Content-Type': 'application/json'},
});
// β
const response = Response.json({error: 'Not found'}, {status: 404});