Failed to fetch CORS error: Express body limit and order
A Failed to fetch CORS error can hide a 413 from Express. How a body limit and CORS middleware order masked the real error, and the setup that shows the cause.
By Hamza Ghouri
A "Failed to fetch" CORS error in the browser tells you almost nothing. It says the request did not produce a response the page was allowed to read, and that is all. The real cause can be anything from a server that is down to a perfectly ordinary 413. I hit this on the admin panel of a photo marketplace, where saving a blog post with an image pasted into it failed with a bare "Failed to fetch". Two faults were stacked on top of each other, and the second one hid the first. This post walks through both, the Express setup I use now, and how to find the real error behind a network failure.
The symptom: a save that failed with no detail
The blog editor lives in the admin panel and posts JSON to an Express API. Saving a text-only post worked. Saving a post with an image pasted into the body failed, and the only thing the browser had to say was "Failed to fetch". No status code, no message, nothing in the response tab.
That looks like a network problem, so the first instinct is to blame the connection, the proxy or the server being down. None of those were the cause. The server was up and answering. It was answering with an error the browser refused to show.
Fault one: express.json() and the 100kb default
express.json() was registered with no options. Its default limit is 100kb, which the body-parser documentation lists along with the error it raises when a body is larger: status 413 with type set to entity.too.large.
100kb is plenty for most JSON APIs. It is nothing for a rich-text editor that inlines pasted images as base64 data URIs. One screenshot in the body passes that limit straight away, so the parser rejected the request before any route code ran.
On its own, that would have been an easy bug. The browser would have shown a 413 and the fix would have been obvious. The reason it showed "Failed to fetch" instead was the order of the middleware.
Fault two: CORS middleware registered after the body parser
cors() was registered after express.json(). When the body parser rejects a request, Express skips every remaining normal middleware and goes straight to the error handlers. So the CORS middleware never ran, and the error response went out with no Access-Control-Allow-Origin header.
The admin panel runs on a different origin from the API. Without that header, the browser is not allowed to hand the response to the page. It blocked a response it could not read and reported a network error, which hid both the status and the message.
I confirmed this against production before changing anything. A 293kb body came back as a 500 with no access-control-allow-origin header. A small body came back as a 400 with the header present. Same route, same origin. The only difference was whether the request got far enough for CORS to run.
The 500 was its own story. A leftover debug error handler, registered ahead of the main error middleware, answered every error with a 500, so the typed error mapping below it never ran. That is the same class of bug: middleware order deciding what the client sees. It came out in a separate audit and is gone now.
Why does a CORS error say Failed to fetch?
Because the browser is not allowed to tell the page anything else. When a cross-origin response lacks the right CORS headers, the browser withholds the status, headers and body from your code and fetch rejects with a generic TypeError, which Chrome shows as "Failed to fetch". The MDN guide to CORS explains that these failures are deliberately opaque to JavaScript. The real status is still visible in the browser's Network tab and in your server logs.
The Express setup I use now
Three changes, all in the app setup:
cors()runs first, before any body parser or route, so every response carries the CORS headers, including errors.- The JSON limit is set on purpose. I set it to 10mb. nginx in front of the API already allowed 50m, so the app was the tightest limit by far.
- Body-parser failures map to real statuses with messages that name the cause: 413 for a body that is too large and 400 for JSON that does not parse.
import express from "express";
import cors from "cors";
const app = express();
app.use(cors({ origin: allowedOrigins }));
app.use(express.json({ limit: "10mb" }));
// ...routes...
app.use((err, req, res, next) => {
if (err.type === "entity.too.large") {
return res.status(413).json({ message: "Request body is larger than 10 MB." });
}
if (err.type === "entity.parse.failed") {
return res.status(400).json({ message: "Request body is not valid JSON." });
}
next(err);
});
With cors() first, the headers are set on the response before the parser runs, so even a rejected body reaches the page as a readable 413. The editor can then show "too large" instead of a network error.
Fix the payload, too: base64 images do not belong in the body
Raising the limit made the error readable. It did not make inlined images a good idea. A base64 image is about a third larger than the file, it sits inside the stored HTML, and every reader downloads it as part of the page. Here it would have shipped megabytes of HTML to every reader before a word of text rendered.
So the editor now uploads inserted images to Cloudflare Images and stores only the URL in the post body. The request stays small, the HTML stays small, and the image gets served from a CDN with its own caching. If you are building the upload side, I covered the sharp edges of signed uploads in presigned URL Content-Type and caching gotchas, and resizing in image processing pipelines with Sharp and S3.
One trap in that change: the editor's React wrapper typed its image-upload hook with three parameters, while the underlying plugin passes four. Writing the handler to match the declared type would have read the editor's core object as the upload callback and dropped every upload. I matched the plugin's real signature instead. When a wrapper's types and the library disagree, the runtime wins.
Same editor, another vague error: optional fields
The same editor surfaced one more confusing error. A zod schema marked the slug as .optional(), which accepts undefined and rejects an empty string. An untouched HTML input sends "", so the "optional" slug could never be left blank, and the error did not name the field.
The fix was a small helper that treats an empty string as absent, applied only to fields the server fills in itself, such as an auto-generated slug. Other fields keep rejecting blanks, because an empty string there is usually a mistake the user should see.
How to debug a Failed to fetch CORS error
My checklist when a browser says "Failed to fetch":
- Open the Network tab and look at the failed request. If it has a status code, the server answered and the problem is headers, not the network.
- Check for
Access-Control-Allow-Originon that response. A missing header on an error response usually means CORS runs after something that can fail. - Replay the request with
curl, including theOriginheader, so you see the status and body the browser hid. - Read the middleware order top to bottom. Anything that can throw before
cors()will produce errors the page cannot read.
Timeouts produce a similar confusion in mobile apps, where a request the server completes shows up as a failure. I wrote about that in fixing a slow API endpoint by replying first.
The short version
"Failed to fetch" on a cross-origin call often means the server returned an error without CORS headers. Register cors() before body parsers and routes, set the JSON limit deliberately, and map body-parser errors to 413 and 400 with clear messages. Then stop sending images inside JSON at all. If your API needs this kind of cleanup, it is work I take on through my services.