Cloudflare Function responses always have 200 status code

I’ve tested a variety of methods for returning a redirect but any response (even an error) from a Cloudflare Pages function returns a 200 OK status code to the client. This means things like Mailchannel middleware can only deal with HTML or plain text responses. You can’t redirect to a thank you page (such as the one detailed in your feature release blog - that code no longer works).

I’ve mocked up a test function on this route.

And the functions code is:

// /functions/test.js
export function onRequest(context) {
    return Response.redirect("", 302)

I’ve also tested this on a worker, and the code worked as expected. It sent the status code, header, and the browser immediately redirects. The response I get from the above function is a 200 OK, I can see the location header is set but it has changed the response code.

Your code looks fine to me, Response.redirect() works for me, and your test function redirects with a 302 status code for me.

> curl --include
HTTP/2 302
date: Thu, 15 Dec 2022 18:56:05 GMT
content-length: 0

Thanks for pointing that out, I removed the mailchannel middleware and didn’t test after.

It appears the bug is in the middleware itself. I’ve added it back in and now the redirect fails.

I’ve implemented the code found here, with the email addresses switched out for my own domain. Sends emails fine but breaks redirects from Response objects.

Now if you test you can see the 200 OK response code. The test.js function is still setting the Location header but something in the middleware has altered the status code.

Did you figure it out? I still get:

> curl --include
HTTP/2 302
date: Fri, 16 Dec 2022 20:02:25 GMT
content-length: 0

Figured it out. There’s bugs in the NPM packages.

The underlying bug is actually in the “Static Forms Pages Plugin” which mutates the Response object by creating a new one and copying all its attributes. The problem is it’s not copying the status code which is reset to 200 OK.

return new Response([101, 204, 205, 304].includes(response.status) ? null : response.body, { …response, headers: new Headers(response.headers) });

Because it’s deployed with middleware, it then breaks all routes on your site for GET or POST requests. Oof.

Mailchannel plugin is a mangled version of the Static Forms code. And so the same bug has been copied over.

I’ve heavily refactored the index.js in the Mailchannel package, it was a real mess. I’ve also fixed the bug in Static forms plugin as well (it’s just that one line).

Here’s the fixed Mailchannels plugin:

And the fixed Static Forms plugin:

I’ve added extra documentation to both for easier use. Hopefully people having the same problem with redirects on the Mailchannel plugin find it.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.