I'm building a user auth in the backend. I created a post method for registering a new user
userRouter.post("/", expressAsyncHandler(async (req, res) =>
{
try {
const { name, email, password } = req.body;
const userExists = await User.findOne({ email });
if (userExists) {
res.status(400).json({ message: "User already exists" });
}
const user = await User.create({
name,
email,
password,
});
if (user) {
res.status(201).json({
data: {
_id: user._id,
name: user.name,
email: user.email,
token: generateToken(user._id),
},
});
} else {
res.status(400).json({ message: "Registration failed" });
}
} catch (error) {
res.status(500).json({message:error.message})
}
}))
It is working but shows
Cannot set headers after they send it to the client
I'm feeling a little uncomfortable with this code. so how can I make the code cleaner and more efficient? what are the best practices to follow?
Thanks in advance :)