Sign-up Form In NextJs

import connect from "@/config/config";
import User from "@/models/user";
import { NextResponse } from "next/server";
import bcryptjs from "bcryptjs";

connect();

export async function POST(request) {
    try {
        // Parse request body
        const reqBody = await request.json();
        const { name, email, password } = reqBody;

        // Validate required fields
        if (!name || !email || !password) {
            return NextResponse.json(
                { error: "All fields (name, email, password) are required", success: false },
                { status: 400 }
            );
        }

        // Check if user already exists
        const user = await User.findOne({ email });
        if (user) {
            return NextResponse.json(
                { error: "User already exists", success: false },
                { status: 400 }
            );
        }

        // Hash the password
        const salt = await bcryptjs.genSalt(10);
        const hashedPassword = await bcryptjs.hash(password, salt);

        // Create and save new user
        const newUser = new User({
            name,
            email,
            password: hashedPassword,
        });
        const savedUser = await newUser.save();

        // Respond with success
        return NextResponse.json(
            {
                message: "User created successfully",
                success: true,
                user: savedUser,
            },
            { status: 201 }
        );
    } catch (error) {
        console.error("Error while creating user:", error.message);
        return NextResponse.json(
            { error: "Internal Server Error", success: false },
            { status: 500 }
        );
    }
}