Why is Authorization present in a Fetch Request but missing when the request is sent?

May 12, 2025

On May 12, 2025, I was developing Express Http Client and integrating it into the frontend of an asset management project. The library adds Express-style middleware around Fetch for consistent authentication and response handling. I hit an apparent contradiction: the Request logged by the middleware already had an Authorization header, but the outgoing request didn't.

I asked Cursor:

“here logs Request interceptor 1 has auth header but the request sent doesn't have auth header why”1

To understand what happened, follow three layers: how Fetch accepts a request, which parts of a Request can change, and how modifications inside a JavaScript function reach the caller. After resolving that, refreshing a token and resending raises another question: a request body can only be consumed once.

Let's start with an ordinary Fetch call. The examples were rewritten during editing to explain the principles and use fictional addresses and tokens. For the original motivation and interface trade-offs, see the design discussion.

From fetch(url, options) to a Request object

A common pattern passes a URL to fetch and supplies the method, headers, and body in the second argument. You can also construct a Request first and hand it to Fetch. Each object has a distinct role:2

InterfaceRole
fetch(input, options)Sends the request and returns a Promise that resolves to a Response.
RequestRepresents a request to be sent, including its URL, method, headers, and body.
HeadersManages HTTP header names and values with methods such as get(), set(), and append().
ResponseRepresents the response, exposing its status, headers, and ways to read its body.

For example, explicitly separate preparing the request from sending it:

const request = new Request("https://example.com/api/items", {
  method: "GET",
  headers: { Accept: "application/json" },
});

const response = await fetch(request);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const items = await response.json();

new Request(...) just constructs an object. It doesn't contact the network. fetch may reject on a network error, but HTTP statuses like 401, 404, or 500 normally still yield a Response, so check status or ok yourself. response.json() is another asynchronous operation that reads and parses the response body.2

Read-only Request properties don't make everything immutable

Earlier in the same debugging session I asked:

“how can i update request object created by new Request here”1

I looked through body, headers, method, url, and integrity to understand what my wrapper would need to preserve from the native Request. For example, integrity records the resource integrity value the caller supplied. Two other details actually determined the authentication fix: which object received the header, and whether the body remained readable after the first send.34

Consider method, which MDN marks read-only:

“The method read-only property of the Request interface contains the request's method (GET, POST, etc.)”5

You read the method through request.method. Assigning request.method = "POST" doesn't change it. To change a constructor option like this, construct another Request:6

const original = new Request("https://example.com/api/items");
const updated = new Request(original, { method: "POST" });

console.log(original.method); // GET
console.log(updated.method);  // POST

Adding query parameters to a GET address changes the URL. That's the scenario in a Stack Overflow question I found at the time. Create new URL(original.url), update parameters with searchParams.set(), then use the new address and the options you want to preserve to construct a Request. A token refresh keeps the address and replaces the authentication header.7

The original request here is bodyless so we can isolate the method change. In general, the constructor validates combinations of method, body, and other options. For example, GET and HEAD requests cannot carry bodies. Whether an existing request body is still usable also affects reconstruction, as we'll see below.62

For headers, distinguish two levels. The Request's headers property is read-only: you can't assign a different Headers object to it. But when the referenced Headers is mutable, you can update its contents with .set(). For an ordinary request you've constructed yourself, for example, call request.headers.set("Authorization", "Bearer example-token") before sending.8

Not every Headers object permits arbitrary changes. Browsers restrict some request headers, and no-cors mode narrows the allowed set further. You can't directly modify the headers on a network response returned by Fetch either. Check both whether the property is assignable and what mutations the Headers object permits.8

Why didn't the new Request escape the function?

Even constructing a new object correctly with new Request(...) can produce my symptom. Here's a minimal reproduction requiring no network request:

const original = new Request("https://example.com/api/items");

function replaceLocally(request) {
  const headers = new Headers(request.headers);
  headers.set("Authorization", "Bearer example-token");
  request = new Request(request, { headers });
  console.log(request.headers.get("Authorization")); // Bearer example-token
}

replaceLocally(original);
console.log(original.headers.get("Authorization")); // null

On function entry, the local parameter request and outside variable original refer to the same object. After the assignment, the local parameter refers to the new object while original still points to the old one. Logging the new object inside the function works. Calling fetch(original) outside still sends the old request.

These are JavaScript's argument-passing rules. When you pass an object, the value passed is its reference. Other code sharing that object sees changes to its properties. Reassigning a local parameter doesn't replace the caller's variable.9

Make the change visible: return the new object or update a shared property

For an ordinary helper, the most direct option is to return the new Request and have the caller receive it:

function withAuthorization(request, token) {
  const headers = new Headers(request.headers);
  headers.set("Authorization", `Bearer ${token}`);
  return new Request(request, { headers });
}

let request = new Request("https://example.com/api/items");
request = withAuthorization(request, "example-token");
const response = await fetch(request);

This copies Headers to preserve the other request headers, then replaces Authorization.10 Again the request is a bodyless GET so we can focus on object replacement without mixing in body consumption.

If the interface expects callbacks to share state, put the request in an ordinary object. This example illustrates just the data flow without introducing a middleware library:

const data = {
  request: new Request("https://example.com/api/items"),
};

function addAuthorization(data) {
  const headers = new Headers(data.request.headers);
  headers.set("Authorization", "Bearer example-token");
  data.request = new Request(data.request, { headers });
}

addAuthorization(data);
const response = await fetch(data.request);

Now the assignment updates the shared object's request property. Reading data.request outside retrieves the new Request. My middleware needed next() to advance the chain and carry errors, so I chose this shared-state approach. The May 12 prototype already contained the structure.11

To update only a mutable request header, you can also call request.headers.set() directly as above. The choice depends on whether you need to replace construction options such as the method and whether the caller wants to retain the original object.

Why prefer Headers.set() for authentication updates?

Headers and ordinary JavaScript objects handle names differently. An ordinary object can have separate authorization and Authorization keys. HTTP header names match case-insensitively. If you spread old headers into a plain object and add another key with different capitalization, constructing Headers from it may combine the values:8

const previous = new Headers({ authorization: "Bearer old-token" });
const combined = new Headers({
  ...Object.fromEntries(previous),
  Authorization: "Bearer new-token",
});
console.log(combined.get("authorization"));
// Bearer old-token, Bearer new-token

const replaced = new Headers(previous);
replaced.set("Authorization", "Bearer new-token");
console.log(replaced.get("authorization")); // Bearer new-token

.set() replaces the value for that name. .append() adds another value. A token update needs to replace old credentials, so .set() expresses the operation more clearly than combining ordinary objects. The tokens in this example are fictional.12

In the asset management code committed on May 21, the two paths differed. For the initial send, the interceptor already wrote the new object back to data.request, so the sender saw the modified request. It still added the authentication header using the plain-object spread above, however. If the caller already supplied authorization, duplicate values remained possible. After a successful refresh on 401, the retry branch used new Headers(data.request.headers) and .set() to keep only the new token, then handed a new request to Fetch.13

A surviving Request object doesn't mean its body can be sent again

Once object replacement is fixed, retries still have to account for one fact: the body is a stream and may already have been consumed by a read or send. Having the original Request variable in scope doesn't mean you can send the same body with it again.14

MDN describes this limit on clone():

“clone() throws a TypeError if the request body has already been used.”14

To keep a copy of a request with a body, clone it before its first consumption. This network-free example uses .text() to simulate consuming it:

const request = new Request("https://example.com/api/search", {
  method: "POST",
  body: JSON.stringify({ query: "keyboard" }),
});
const backup = request.clone(); // 在读取或发送前保存副本

await request.text();
console.log(request.bodyUsed); // true
console.log(await backup.text()); // {"query":"keyboard"}

For small JSON requests, another straightforward approach is to keep the serialized string and construct a fresh Request each time you need to send:

const body = JSON.stringify({ query: "keyboard" });
function makeRequest(token) {
  return new Request("https://example.com/api/search", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body,
  });
}

Call makeRequest(oldToken) for the first send. After refreshing the token, call makeRequest(newToken) if a retry really is needed. Each call has a new body. This only handles reconstruction. Whether a retry is permitted or could duplicate a business operation depends on the API contract.

For large uploads and continuous streams, cloning isn't a free backup. It creates two reading branches. Unread data may accumulate on the slower side. Decide how to replay such requests based on the data source; you can't retain copies without limit.14

When debugging similar issues now, I trace the actual data: which Request was constructed, whether the function changed a property or its local variable, which object finally reached Fetch, and whether its body had already been consumed. A log tells you what was present at the point of logging. Following the object all the way to the send explains what actually went out.

References

Footnotes

  1. CaiBorui. (2025, May 12). Updating Request Object in JavaScript [Private development conversation with Cursor, asset management workspace, retained by the author]. Cursor. The quotations are from messages 5 and 1, next to assistant replies at about 15:35 and 15:12 (UTC+8) respectively. Messages 7 and 9 continue on request replacement and local references. User messages have no independent timestamps and are located by neighboring assistant replies. Checked November 17, 2026. The complete conversation and actual credentials are not published. ↩ ↩2

  2. MDN contributors. (2025, August 20). Using the Fetch API [Making a request, Setting a body, Handling the response]. MDN Web Docs. Retrieved November 17, 2026, from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch . See also MDN contributors. (2026, June 8). Fetch API [Concepts and usage]. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#concepts_and_usage . The dates are modification dates shown on the pages at review, not May 2025 snapshots. ↩ ↩2 ↩3

  3. MDN contributors. (n.d.). Request: integrity property. MDN Web Docs. Value, integrity supplied at construction. ↩

  4. CaiBorui. (2026, November 25). Looking up Fetch and Request compatibility [Author's recollection and local Firefox visit history]. Filed under the debugging date. On 2025-05-12 from 15:07 to 15:10 Beijing time I consulted the Request constructor, method, RequestInit, body, headers, integrity, and related pages in sequence and searched for updating a Request. The next day I continued with Headers.set, the Headers constructor, changing a new Request's URL, and Headers.append. A separate earlier sequence of visits to Using Fetch, Fetch API, Request, and Request.method is known in order but hasn't been individually dated. ↩

  5. MDN contributors. (2025, March 13). Request: method property [Opening definition]. MDN Web Docs. Retrieved November 17, 2026, from https://developer.mozilla.org/en-US/docs/Web/API/Request/method . March 13 is the page's modification date, not my visit date. ↩

  6. MDN contributors. (2026, October 12). Request: Request() constructor [Parameters, Exceptions]. MDN Web Docs. Retrieved November 17, 2026, from https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#parameters . ↩ ↩2

  7. zik. (2017, March 24). Modify the URL of a new Request Object in ES6 [Question]. Stack Overflow. Original example appending query parameters. ↩

  8. MDN contributors. (2026, November 13). Headers [Description, Modification restrictions]. MDN Web Docs. Retrieved November 17, 2026, from https://developer.mozilla.org/en-US/docs/Web/API/Headers#description . For the property itself, see MDN contributors. (n.d.). Request: headers property. MDN Web Docs. See also Request [Instance properties], revised the same day. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Request#instance_properties . ↩ ↩2 ↩3

  9. MDN contributors. (2025, July 8). Functions [Declaring functions, pass-by-value arguments and changing object properties]. MDN Web Docs. Retrieved November 17, 2026, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#declaring_functions . ↩

  10. MDN contributors. (n.d.). Headers: Headers() constructor. MDN Web Docs. Examples, copying from existing Headers. ↩

  11. Cai, B. [S2thend]. (2025, May 12). First functional prototype version [Commit 40899b4, index.js and README]. GitHub. https://github.com/S2thend/express-http-client/commit/40899b496cad46b59f238fa0ad72f78f11691e0b . The shared-object example simplifies that mechanism and isn't a verbatim extract of the historical code. The commit establishes implementation; conversation suggestions alone don't. ↩

  12. MDN contributors. (2025, March 13). Headers: set() method [Opening distinction between set and append]. MDN Web Docs. Retrieved November 17, 2026, from set(), overwriting an existing value. See also MDN contributors. (n.d.). Headers: append() method. MDN Web Docs. append(), adding to an existing value. ↩

  13. CaiBorui. (2025, May 21). Add support for express http handler [Local asset management project Git commit 54933d5]. See the request interceptor at the start of frontend/src/utils/ExpressHttpHandler.js and the retry branch following a successful refresh. ↩

  14. MDN contributors. (2025, March 13). Request: clone() method [Opening discussion of body consumption, TypeError, and buffering stream branches]. MDN Web Docs. Retrieved November 17, 2026, from https://developer.mozilla.org/en-US/docs/Web/API/Request/clone . The quotation comes from the introductory TypeError paragraph. The cloning and reconstruction examples were added during editing and do not establish that the project already implemented complete retries at the time. ↩ ↩2 ↩3

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-12). Why is Authorization present in a Fetch Request but missing when the request is sent?. https://caiborui.com/blog/2025-05-12-zh-fetch-request-mutation-and-retry-entrans

@misc{borui2025-177ccb83,
  author = {borui},
  title = {{Why is Authorization present in a Fetch Request but missing when the request is sent?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-12-zh-fetch-request-mutation-and-retry-entrans}
}