0

I'm using Express to create an API endpoint for user registration. The problem is, whenever I send a request that will initiate an error to that API endpoint, my node.js server crashes and gives me the following message:

node:internal/errors:491
[1]     ErrorCaptureStackTrace(err);
[1]     ^
[1]
[1] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent 
to the client
[1]     at new NodeError (node:internal/errors:400:5)
[1]     at ServerResponse.setHeader (node:_http_outgoing:663:11)
[1]     at ServerResponse.header (D:\...\node_modules\express\lib\response.js:794:10)
[1]     at ServerResponse.send (D:\...\node_modul

So, the node.js server crashes whenever is sending an error (fail) response, but when it's sending success response it doesn't crash. So I guess I'm not handling errors proper here?

What I'm doing wrong here? Here is my implementation:

const registerUser = async (req: Request, res: Response) => {
  try {
    const userData = createUserSchema.parse(req.body) as User;

    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(userData.password, salt);

    const user = await db.user.create({
      data: {
        ...userData,
        password: hashedPassword,
      },
    });

    return res.status(201).json({
      status: 'success',
      data: { name: user.name, email: user.email },
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return res.status(422).json({
        status: 'fail',
        message: error.issues,
      });
    } else if (error instanceof Prisma.PrismaClientKnownRequestError) {
      if (error.code === 'P2002') {
        return res.status(409).json({
          status: 'fail',
          message: 'Email address is already in use',
        });
      }
    }

    return res.status(500).json({
      status: 'fail',
      message: 'Something went wrong',
    });
  }
};

I've tried to return error only for one case to see if these responses are conflicting but even if I have only one response, node.js server crashes.

1 Answers1

1

This error occurs because you are trying to set the response headers after they have already been sent to the client. In Express, you cannot set response headers after sending a response body part. This error occurs when you try to send an error (fail) response after you have already sent a response body part or a success response.

To fix this, make sure you're handling errors appropriately in your code. Make sure you don't send more than one response to the client for a single request. You can use the Express Error Handling Middleware to catch errors and send an appropriate response to the client without throwing an "ERR_HTTP_HEADERS_SENT" error.

Try with middleware like this:

app.use((err, req, res, next) => {
    console.error(err);

    res.status(500).json({
     status: 'fail',
     message: 'Something went wrong',
    });
});

https://expressjs.com/en/guide/using-middleware.html

Using express middlware will save you a lot of effort

My Stack Overfloweth
  • 4,729
  • 4
  • 25
  • 42