Why does calling res.status().json() cause this error?

208 Views Asked by At

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'
}
0

There are 0 best solutions below