Stack Exchange
Why does calling res.status().json() cause this error?
I'm trying to implement authentication with argon2, and the line that crashes the app is highlighted in the following code snippet.
const { readFileSync } = require("fs");
const { Router } = require("express");
const users = require("../users.json");
const { verify } = require("argon2");
const { sign } = require("jsonwebtoken");

const key = readFileSync("key");
const expiresIn = process.env.JWT_MAX_AGE || "1d";

const router = Router();

router.post("/", async (req, res) => {
    const { phone_number, password } = req.body;

    const user = users.find((user) => user.phone_number === phone_number);

    if (!user) {
        res.status(401).json({ message: "Invalid username/password" });
        return;
    }

    if (!await verify(user.password_hash, password)) {
        // CRASH: This line crashes the app
        res.status(401).json({ message: "Invalid username/password" });
        return;
    }

    const { id } = user;

    sign({ id }, key, { expiresIn }, (err, token) => {
        if (err) {
            res.status(500).json({ message: "Something went wrong" });
            return;
        }

        res.status(200).json({ token });
    });
});

module.exports = router;

I got the following output after POSTing credentials with an existing username and an invalid password. May I know what could possibly go wrong in this case? Thanks!
node:internal/errors:465
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: 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 (/Users/user/Repositories/backend/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/Users/user/Repositories/backend/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/Users/user/Repositories/backend/node_modules/express/lib/response.js:278:15)
    at /Users/user/Repositories/backend/routes/sign_in.js:23:25 {
  code: 'ERR_HTTP_HEADERS_SENT'
}


So if you're passing a non-existent username/phone number, you don't get an error?

@robertklep Yup, I don't get the same error if I pass a non-existent username, meaning that the if-statement above the CRASH line does work as expected.

Are you using any middleware that might be causing it?

@robertklep but I do get response if I pass in non-existent username/phone number, that should have passed all middlewares before reaching the /signin route, am I right?

Yes, unless you have a custom middleware that somehow could be causing it.
