'Error: Cannot set headers after they are sent to the client - Node express/typescript

Heyho. I get Cannot set headers after they are sent to the client error on res.redirect.

This part of the code is called from a verification e-mail. After the button is clicked everything runs fine, but when it comes to redirect it throws the error.

@Get('/validate')
async validate(
    @QueryParam('token') token: string,
    @Res() res: Response,
): Promise<void> {
    const usersByToken = await (this.repository as UserRepository).getByToken(token);
    let isvalid = false;
    if (usersByToken.length !== 1) {
        isvalid = false;

    }
    if (!isBlacklisted(usersByToken[0].email)) {
        const uni = isUniversity(usersByToken[0].email);
        const organizationcontroller = new OrganizationController();
        const org = await organizationcontroller.getByName(uni);
        if (!org) {
            await sendAdminEmail(usersByToken[0].email);
            isvalid = false;
        } else {
            const update = await (this.repository as UserRepository).validateUser(token, org);
            if (update.affected > 0) {
                isvalid = true;
            }
        }

    } else {
        isvalid = false;
    }

    if (isvalid) {            
        return res.status(200).redirect(`/login;validation=ok;email=${usersByToken[0].email}`);
    } else {            
        return res.redirect('/login;validation=invalid');
    }
}

And here is the error message:

Error: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (D:\Egyetem\szakdoga\backend\node_modules\express\lib\response.js:776:10)
at ServerResponse.json (D:\Egyetem\szakdoga\backend\node_modules\express\lib\response.js:264:10)
at ExpressDriver.handleError (D:\Egyetem\szakdoga\backend\node_modules\src\driver\express\ExpressDriver.ts:377:18)
at D:\Egyetem\szakdoga\backend\node_modules\src\RoutingControllers.ts:128:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)

In theory nothin else is called with a response, so i dont know what causes the error.



Solution 1:[1]

It's as the error states, you can't set headers after they're sent to the client. Since you don't have a repro example, I would assume somewhere along that block you unknowingly sent a response to the client.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anthony Ma