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.