unicorn/no-invalid-fetch-options

Disallow a body in fetch() and new Request() when the method is GET or HEAD

A GET or HEAD request can't have a body. If you give it one, new Request() throws a TypeError and fetch() rejects with one. The method defaults to GET, so the usual cause is a forgotten method: "POST".

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/no-invalid-fetch-options" = "error" # or "warn"

Examples#

example.js1 problem
function createUser(user) {
  return fetch("/api/users", {
    body: JSON.stringify(user),
  });
}
example.js1 problem
const request = new Request("/api/users", {
  method: "HEAD",
  body: "name=Ada",
});
example.jsNo problems
function createUser(user) {
  return fetch("/api/users", {
    method: "POST",
    body: JSON.stringify(user),
  });
}

A body of undefined or null is allowed. The rule also stays quiet when it can't tell what the method or the options are, for example when the object has a spread:

example.jsNo problems
fetch("/api/users", { body: undefined });
fetch("/api/users", { ...defaults, body: "name=Ada" });
fetch("/api/users", { method: getMethod(), body: "name=Ada" });