Happy Netlify customer here for many years.
It looks like Netlify docs & functions are in the middle of a transition? Which really stinks if you are a newbie coming in and trying out Functions functionality.
I just spent an evening and a morning trying to figure out how to return a status code using the default recommended function template:
All of the docs show this:
export default async (req, context) => {
return new Response("Hello, world!");
};
(Link: Get started with functions | Netlify Docs)
Which appears to be the new blessed way to do this.
But if you go through the rest of the docs, the following format is used:
const handler: Handler = async function (event: HandlerEvent, context: HandlerContext) {
//...
}
And if you aren’t paying close attention, you’ll miss that. It’s cognitive overload that one doesn’t need when you are scanning info on how to do something: “Is this the old way or the new way?”
Now to the point: how do you return a 404 status code along with some JSON?
Well, looking at the Netlify docs, it’s quite obviously:
return {
body: JSON.stringify({}),
statusCode: 404
}
And, that’s also further cemented as the way according to all the searches here on answers.netlify.com and google.com
But it’s not. It’s:
return new Response(JSON.stringify({}), { status: 404 });
(Which I only figured out by going through Mozilla developer docs: Response: Response() constructor - Web APIs | MDN)
And to my last point, finding out WHY you are getting a blank 500 error code with absolutely no exception thrown, no error message, nothing in the logs on development and production is really, really frustrating.
It appears (and maybe this was stated in the docs some place that I missed) that if you access the function locally in a browser, instead of via a JS fetch or RapidAPI test call, you will get an HTML page that explains more and includes a stack trace.
But why oh why isn’t that message shown in the local CLI logs? I only stumbled upon this by accident.
Some of this is me venting. But mostly this is feedback to improve the docs and also for anyone else that comes through here in the future trying to find out how to return a response with a status code from a Function.