Skip to content

Latest commit

Β 

History

History
45 lines (32 loc) Β· 1.59 KB

prefer-response-static-json.md

File metadata and controls

45 lines (32 loc) Β· 1.59 KB

prefer-response-static-json

πŸ“ 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.

Examples

// ❌
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});