Skip to content

How to handle canceled requests? #658

@danechitoaie

Description

@danechitoaie

Hi,
Any idea how to properly handle aborted requests by the clients and abort other requests further down the line?
I have an endpoint in my Fastify app that acts as a middleware where users make requests and then I get some data from some other external API. Now when a user aborts the request done from him to my middleware I need to catch that so that I can also abort the request that I'm doing to the other API.

I have the following code but when I do curl / postman to my 127.0.0.1:8000/data endpoint I instantly get 204 response always.

Any idea what's wrong with the code bellow? As I would expect to get to the request.raw.on("close", () => { only if I close the request from client before waiting for the response, but somehow it always gets there instantly and my external fetch request never finishes executing.

export default async (app: FastifyInstance, options: FastifyPluginOptions) => {
    app.post("/data", { schema }, async (request: FastifyRequest, reply: FastifyReply) => {
        const abortController = new AbortController();

        request.raw
            .on("close", () => {
                abortController.abort();
            })
            .on("error", () => {
                abortController.abort();
            });

        const {
            body: { data },
        } = request;
        try {
            const res = await fetch("https://....", { signal: abortController.signal });
            return await res.json();
        } catch (err: any) {
            if (abortController.signal.aborted) {
                reply.status(204).send();
                return;
            }

            reply.internalServerError();
            return;
        }
    });
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions