Custom Signup form sets session but does not log the user in

Good morning all, I would appreciate some help if possible please

Question:
I have created a custom signup form because we are in need of collecting some specific data at registration.
The form works, it signs the user up and collects the data required, but it does not work smoothly and it does not log the user into the site.

Product:
Wix Website Editor & Velo

What are you trying to achieve:
Currently I am not getting the ‘Member Logged in Success message’, and the user is not being signed in. However they are signed up to wix (I get the notification) and the db insert is made correctly.

What have you already tried:
I think the issue is a bit of a mismatch of code and if I put in the // areas it gives me the success message but then also a failed message saying the user exists, so it looks like I am looping the request.

Additional information:
If you see any other ways for me to be more efficient in the code I am open to ideas. I spend a lot of time scouring this site for ideas and best practices, I am not an expert by far but believe I have a fairly good understanding, but all ideas and help is appreciated.

Screenshot is the logs for the site showing (what I believe) is a success registration, db insert (extra member fields) and finally a successful login.

Last point - I haven’t yet added code to restrict the dates to check if the user is under 13. Any ideas on this welcomed. I tried using the frontend, but couldnt get it to restrict based on dates without having to consistently update it.

Thank you in advance all.

//From Page - Signup Form
import { authentication } from "wix-members.v2";
import wixData from 'wix-data';
import wixLocation from 'wix-location'; 
import wixWindow from 'wix-window';

$w.onReady(async () => {
    //Clear Dropdown
    $w("#dropdownclub2").options = []

    //Sets up a dropdown for the clubs in a collection
    const query = await wixData
        .query("OmanBasedClubs")
        .ascending("orderby", "title")
        .find() // Run the query
        .then((results) => {
            if (results.items.length > 0) {
                let item = (results.items[0]);
                for (var i = 0; i < results.items.length; i++) {
                    let opts = $w('#dropdownclub2').options;
                    let x = (i).toString();
                    opts.push({ label: results.items[x].title, value: results.items[x].title });
                    $w('#dropdownclub2').options = opts;
                }
            } else {
                console.log("No Clubs found");
            }
        });
})

$w.onReady(function () {
    const errormessageReset = () => {
        $w("#errormessage").hide();
        const reg = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,16}$/
        $w("#passwordconfirminput").onCustomValidation((value, reject) => {
            if ($w("#passwordinput").value !== $w("#passwordconfirminput").value) {
                $w("#errormessage").text = "Your passwords do not match.";
                $w("#errormessage").show();
                $w("#signupbutton").disable();
            } else {
                $w("#passwordinput").onCustomValidation((value, reject) => {
                    if (!reg.test($w("#passwordinput").value)) {
                        $w("#errormessage").text = "Your passwords are not validated correctly.";
                        $w("#errormessage").show();
                        $w("#signupbutton").disable();
                    } else {
                        $w("#signupbutton").enable();
                    }
                });
            }
        });
    }
    $w("#emailinput").onChange(errormessageReset);
    $w("#passwordinput").onChange(errormessageReset);
    $w("#passwordconfirminput").onChange(errormessageReset);
    $w("#firstnameinput").onChange(errormessageReset);
    $w("#familynameinput").onChange(errormessageReset);
    $w("#phoneinput").onChange(errormessageReset);
    $w("#codeinput").onChange(errormessageReset);
    $w("#currentstatus").onChange(errormessageReset);
    $w("#dropdownclub2").onChange(errormessageReset);
    $w("#datebirthPicker1").onChange(errormessageReset);

    const registerNewmember = () => {
        const email = $w("#emailinput").value;
        const password = $w("#passwordinput").value;
        const passwordconfirm = $w("#passwordconfirminput").value;
        const firstname = $w("#firstnameinput").value;
        const familyname = $w("#familynameinput").value;
        const Pstatus = $w("#currentstatus").value;
        const phone = $w("#codeinput").value + $w("#phoneinput").value;
        const currentclub = $w("#dropdownclub2").value;
        const date = $w('#datebirthPicker1').value; // Get the value from the date picker and convert to date for collection
        let dateObject = new Date(date);

        authentication.register(email, password)
            .then((registrationResult) => {
                console.log(registrationResult.member);
                //insert to members collection
                wixData.query("Members")
                    .eq("email", email)
                    .find()
                    .then((results) => {
                        if (results.items.length === 0) {
                            console.log("Inserting Member row");
                            const toInsert = {
                                "HOW": "Signup",
                                "email": email,
                                "firstName": firstname,
                                "lastName": familyname,
                                "phone": phone,
                                "club": currentclub,
                                "currentStatus": Pstatus,
                                "dateofBirth": dateObject.toISOString().substring(0, 10)
                                //Data.js updates the last record if no new unique ID
                            };
                            wixData.insert("Members", toInsert)
                                .catch((err) => {
                                    console.log(err);
                                });
                            console.log("Member inserted", email);
                            $w("#errormessage").hide();
                            $w("#successmessage").text = "Member registered successfully";
                            $w("#successmessage").show();
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    })
                authentication.login(email, password)
                    .then((registrationResult) => {
                            console.log("Member logged in after signup", registrationResult);
                            //wixLocation.to("/"); removed currently whilst trying to sort issue
                        }
                    )
                //Removed next code as it was pulling an error - email already exists - after recieving Member successfully inserted
                // .catch((Error) => {
                //     console.log(Error)
                // });
                wixWindow.lightbox.close();
            }).catch((Error) => {
                console.log(Error)
                $w("#errormessage").text = "There was an error when registering, please check the form";
                $w("#errormessage").show();
            })
    }
    $w("#signupbutton").onClick(registerNewmember);
});```

So some futher updates - positive mainly.

I reviewed a video I found from Queenys site, which helped me figure out a few of my mistakes in the code.

So currently everything works! - except I have 1 final issue that creates a poor user experience .

Current flow:

  • Click signup - signup form appears. All validations work, validations block sign up if an issue, all errors appear and disappear as they should.

Once everything is correct - I press Sign up. After a few seconds I get an error: A member with this email address already exists, Try a different email. However it then closes the lightbox, registers the user, and redirects them to the profile page.
It is also attempting to run the wixData.insert(“Members”, toInsert) again. So it does appear like the code is looping, which would mean the error being shown is a valid error.

So the issue is -
Why does the code appear to be looping to try and register the user again ?

I am obviously missing something so please if anyone can give some ideas I would appreciate it.

I commented out the console logs just for now, but all helped me get through each stage to see where there were any errors in the backend.

The new code is:

`

//Signup page code 
import wixUsers from 'wix-users';
import wixWindow from 'wix-window';
import wixData from 'wix-data';
import wixLocation from 'wix-location';

$w.onReady(function () {
  $w("#dropdownclub2").options = [ ];
  //Sets up a dropdown for the clubs in a collection
wixData
    .query("OmanBasedClubs")
    .ascending("orderby", "title")
    .find() // Run the query
    .then((results) => {
        if (results.items.length > 0) {
            let item = (results.items[0]);
            for (var i = 0; i < results.items.length; i++) {
                let opts = $w('#dropdownclub2').options;
                let x = (i).toString();
                opts.push({ label: results.items[x].title, value: results.items[x].title });
                $w('#dropdownclub2').options = opts;
            }
        } else {
            console.log("No Clubs found");
        }
    }); if (wixUsers.currentUser.loggedIn) {
    wixLocation.to("/account/profile"); // Redirect to profile page
} else {

    let errormessageReset = () => {
        $w("#errormessage").text = "";
        $w("#errormessage").hide();
        $w("#emailexists").hide();
        let reg = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,16}$/

        $w("#passwordconfirminput").onCustomValidation((value, reject) => {
            let ischeckedcc = $w("#codeconductcheck").checked;
            let ischeckedmc = $w("#minorcheck").checked;

            if ($w("#passwordinput").value !== $w("#passwordconfirminput").value) {
                $w("#errormessage").text = "Your passwords do not match.";
                $w("#errormessage").show();
                $w("#signupbutton").disable();
            } else {
                $w("#passwordinput").onCustomValidation((value, reject) => {
                    if (!reg.test($w("#passwordinput").value)) {
                        $w("#errormessage").text = "Your passwords are not validated correctly.";
                        $w("#errormessage").show();
                        $w("#signupbutton").disable();
                    } else {

                        if (ischeckedcc && ischeckedmc) {
                            $w("#signupbutton").enable();
                        } else {
                            $w("#signupbutton").disable();
                        }
                    }
                });
            }
        });
    } // close error message reset
    $w("TextInput").onChange(errormessageReset);
    $w("Dropdown").onChange(errormessageReset);
    $w("DatePicker").onChange(errormessageReset);
    $w("Checkbox").onChange(errormessageReset);

    //check if user is logged in

    if (wixUsers.currentUser.loggedIn) {
        wixLocation.to("/account/profile"); // if yes Redirect to profile page
    }

    //Registermember
    $w("#signupbutton").onClick((event) => {
        //console.log("signup was pressed");
        $w("#errormessage").text = "";
        $w("#errormessage").hide();
        $w("#emailexists").hide();

        if ($w("#emailinput").valid && $w("#passwordinput").valid && $w("#passwordconfirminput").valid && $w("#firstnameinput").valid && $w("#familynameinput").valid && $w("#currentstatus") && $w("#codeinput").valid && $w("#phoneinput").valid) {

            let email = $w("#emailinput").value;
            let password = $w("#passwordinput").value;
            let firstname = $w("#firstnameinput").value;
            let familyname = $w("#familynameinput").value;
            let Pstatus = $w("#currentstatus").value;
            let phone = $w("#codeinput").value + $w("#phoneinput").value;
            let currentclub = $w("#dropdownclub2").value;
            const date = $w('#datebirthPicker1').value; // Get the value from the date picker and convert to date for collection
            let dateObject = new Date(date); // and convert to date for collection insert
            let CCdateObject = new Date();

            wixUsers.register(email, password, {

                    contactInfo: {

                        "firstname": firstname,
                        "lastname": familyname
                    }

                })
                .then((result) => {
                    console.log("Registered:" + email);
                    $w("#errormessage").hide();
                    wixWindow.lightbox.close();

                    wixData.query("Members")
                        .limit(1)
                        .eq("email", email)
                        .find()
                        .then((results) => {
                            if (results.items.length === 0) {
                                // console.log("Inserting Member row");
                                const toInsert = {
                                    "HOW": "Signup",
                                    "email": email,
                                    "firstName": firstname,
                                    "lastName": familyname,
                                    "phone": phone,
                                    "club": currentclub,
                                    "currentStatus": Pstatus,
                                    "codeofconduct": true,
                                    "dateofcoc": CCdateObject,
                                    "over13": true,
                                    "dateofO13Confirm": CCdateObject,
                                    "dateofBirth": dateObject.toISOString().substring(0, 10)
                                    //Data.js updates the last record if no new unique ID
                                };
                                wixData.insert("Members", toInsert)
                                    .catch((err) => {
                                        console.log(err);
                                    });

                                // console.log("Member inserted", email);
                                wixLocation.to("/account/profile"); // Redirect to profile page /account/profile
                            }
                        })

                        // // end of db query
                        // .then((item) => {
                        //     wixLocation.to("/account/profile"); // Redirect to profile page after successful register
                        // })
                        .catch((err) => {
                            let errMsg = err;
                            console.log(err);
                        });

                }).catch((err) => {
                    let errorMsg = err;
                    console.log(err);
                    $w("#emailexists").show();
                });
            console.log("Trying to register");
        } else {
            $w("#errormessage").text = "Missing information in the form. Please check.";
            $w("#errormessage").show();
            $w("#signupbutton").disable();
            // console.log("Missing information when registering");
        }
    }); //signup click end
}
}); // on ready function end

Further to the above, I have developed the code further but still cannot get rid of this frontend error message.

Remember - the code physically works and gets the full desired effect. I am just seeing this error

Key point I have not mentioned, this is on the LIVE site. So not restricted to the preview or test site.

See new code: - any thoughts or help is appreciated!

import wixUsers from 'wix-users';
import wixWindow from 'wix-window';
import wixData from 'wix-data';
import wixLocation from 'wix-location';

let isSignupButtonListenerAdded = false; // Flag to prevent duplicate event listeners
let registrationCompleted = false; // Flag to prevent duplicate registration

$w.onReady(function () {
    // Redirect logged-in users
    if (wixUsers.currentUser.loggedIn) {
        wixLocation.to("/account/profile");
        return; // Stop execution if user is already logged in
    }
    $w("#dropdownclub2").options = [];

    // Fetch and populate dropdown
    wixData.query("OmanBasedClubs")
        .ascending("orderby", "title")
        .find()
        .then((results) => {
            if (results.items.length > 0) {
                let options = results.items.map(item => ({ label: item.title, value: item.title }));
                $w("#dropdownclub2").options = options;
            } else {
                console.log("No Clubs found");
            }
        });

    // Function to validate if the user is at least 13 years old
    function validateAge() {
        let selectedDate = $w("#datebirthPicker1").value;

        // Check if a date has been selected
        if (!selectedDate) {
            return; // Exit if no date is selected
        }
        let birthDate = new Date(selectedDate);
        let today = new Date();

        // Calculate the difference in years
        let age = today.getFullYear() - birthDate.getFullYear();

        // Adjust the age calculation if the birthday has not yet occurred this year
        let birthMonth = birthDate.getMonth();
        let birthDay = birthDate.getDate();
        let currentMonth = today.getMonth();
        let currentDay = today.getDate();

        // If today's date is before their birthday in the current year, subtract 1 year from age
        if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
            age--;
        }
        // Check if the user is under 13
        if (age < 13) {
            $w("#errormessage").text = "You must be at least 13 years old to register.";
            $w("#errormessage").show();
            $w("#signupbutton").disable(); // Disable signup button
            $w("#minorcheck").checked = false;

        } else {
            $w("#errormessage").hide();
        }
    }

    // Attach the function to the date picker change event
    $w("#datebirthPicker1").onChange(validateAge);

    // Reset error messages
    let errormessageReset = () => {
        $w("#errormessage").text = "";
        $w("#errormessage").hide();
        $w("#emailexists").hide();

        let reg = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,16}$/;

        if ($w("#passwordinput").value !== $w("#passwordconfirminput").value) {
            $w("#errormessage").text = "Your passwords do not match.";
            $w("#errormessage").show();
            $w("#signupbutton").disable();
        } else if (!reg.test($w("#passwordinput").value)) {
            $w("#errormessage").text = "Your password is not validated correctly.";
            $w("#errormessage").show();
            $w("#signupbutton").disable();
        } else if ($w("#codeconductcheck").checked && $w("#minorcheck").checked) {
            $w("#signupbutton").enable();
        } else {
            $w("#signupbutton").disable();
        }
    };

    $w("TextInput, Dropdown, Checkbox").onChange(errormessageReset);

    // Add signup button event listener only once
    if (!isSignupButtonListenerAdded) {
        isSignupButtonListenerAdded = true;
        $w("#signupbutton").onClick(() => {
            registerMember();
        });
    }
});

function registerMember() {
    // Prevent function from running multiple times
    if (registrationCompleted) {
        console.log("Registration already completed. Preventing duplicate submission.");
        return;
    }

    // Mark as completed early to prevent multiple executions
    $w("#signupbutton").disable();
    registrationCompleted = true; // Stops a retry
    console.log("Starting registration");

    $w("#errormessage").hide();
    $w("#emailexists").hide();

    if (!($w("#emailinput").valid && $w("#passwordinput").valid && $w("#passwordconfirminput").valid &&
            $w("#firstnameinput").valid && $w("#familynameinput").valid && $w("#currentstatus").valid &&
            $w("#codeinput").valid && $w("#phoneinput").valid && $w("#minorcheck").valid && $w("#codeconductcheck").valid)) {

        $w("#errormessage").text = "Missing information in the form. Please check.";
        $w("#errormessage").show();
        $w("#signupbutton").disable();
        registrationCompleted = false; // Allow retry
        return;
    }

    let email = $w("#emailinput").value;
    let password = $w("#passwordinput").value;
    let firstname = $w("#firstnameinput").value;
    let familyname = $w("#familynameinput").value;
    let Pstatus = $w("#currentstatus").value;
    let phone = $w("#codeinput").value + $w("#phoneinput").value;
    let currentclub = $w("#dropdownclub2").value;
    let dateObject = new Date($w('#datebirthPicker1').value);
    let CCdateObject = new Date();

    // Proceed with Wix Users registration only if the email is not already in use
    return wixData.query("Members")
        .eq("email", email)
        .find()
        .then((results) => {
            if (results.items.length > 0) {
                console.log("User already exists in Members collection.");
                $w("#emailexists").text = "Email is already in use.";
                $w("#emailexists").show();
                registrationCompleted = false; // Allow retry
                return; // Stop the registration process here
            }

            // If email doesn't exist, proceed with Wix Users registration
            return wixUsers.register(email, password, {
                contactInfo: {
                    "firstname": firstname,
                    "lastname": familyname
                }
            });
        })
        .then(() => {
            console.log("Registered: " + email);
            // Insert the new user into the "Members" collection
            return wixData.insert("Members", {
                "HOW": "Signup",
                "email": email,
                "firstName": firstname,
                "lastName": familyname,
                "phone": phone,
                "club": currentclub,
                "currentStatus": Pstatus,
                "codeofconduct": true,
                "dateofcoc": CCdateObject,
                "over13": true,
                "dateofO13Confirm": CCdateObject,
                "dateofBirth": dateObject.toISOString().substring(0, 10)
            }) .catch((insertErr) => {
            console.error("Error inserting member:", insertErr);
            $w("#errormessage").text = "There was an issue completing registration. Please try again.";
            $w("#errormessage").show();
            registrationCompleted = false; // Allow retry
            })
            
        })
        .then(() => {
            console.log("Member inserted", email);
            // Show a success message before redirection

            $w("#successreg").text = "Registration successful! Redirecting...";
            $w("#successreg").expand();
            $w("#errormessage").hide();

            setTimeout(() => {
                wixLocation.to("/account/profile");
            }, 2000);
        })
        .catch((insertErr) => {
            console.error("Error inserting member:", insertErr);
            $w("#errormessage").text = "There was an issue completing registration. Please try again.";
            $w("#errormessage").show();
            registrationCompleted = false; // Allow retry
        });
}

It is possible wixUsers.register() is running twice due to the Page Rendering process for sites built on Wix Studio.

As stated in the article I referenced above:

As a result of the double rendering, any code in your onReady() function may often execute twice, to provide faster initial loading time to access a site

I would verify if this is occurring by using the Rendering API (with env) to ensure it only runs once on the client side.