Validation for duplicate usernames or emails in the sign-up action of a REST API

As I develop a REST API, it is crucial for me to ensure the uniqueness of usernames and email addresses for every user. I have meticulously set up my database models to contain the necessary properties for this purpose. However, when it comes to route logic, I need to verify whether the provided username or email address is both valid and distinct. To achieve this validation process, I utilize the following block of code:

const existingUser = await User.findOne({
    $or: [
        { username: reqData.username },
        { email: reqData.email }
    ]
});

if(existingUser) {
    let errorMessage = '';

    if(existingUser.username === reqData.username) {
       errorMessage = 'This username is already taken.';
    } else if(existingUser.email === reqData.email) {
       errorMessage = 'This e-mail address is already associated with an account.'
    } else {
       errorMessage = 'The provided username or e-mail address is already in use.'
    }

    return res
        .status(400)
        .json({
            message: errorMessage
        });
}

What are your thoughts on the effectiveness of this code? How would you approach designing this validation logic?

On a related note: I am contemplating adding another property like "result" that indicates whether the operation was successful. Do you believe it is best practice to structure the JSON response in the following manner:

return res
    .status(400)
    .json({
        message: errorMessage,
        result: false
    });

Answer №1

It seems that in your current code, the else case

errorMessage = 'User name or e-mail address already in use.';
will never be reached. Therefore, it is redundant.

In addition, you are not accounting for a scenario where both the username and email are the same.

A more effective if logic implementation could look something like this:

if (alreadyExistingUser) {
    let errorMessage = '';

    if (alreadyExistingUser.username === reqData.username) {
        if (alreadyExistingUser.email === reqData.email) {
            errorMessage = 'Both User name and E-mail are already in use.';
        } else {
            errorMessage = 'User name is already in use.';
        }
    } else {
        // If username is not in use, then E-mail is in use
        errorMessage = 'E-mail address is already in use.';
    }

    return res.status(400).json({
        message: errorMessage,
        result: false,
    });
}

Furthermore, in cases where sharing information with the client does not include sensitive data, providing some feedback can be beneficial.

If you prefer not to disclose whether the username or email is in use, you can simplify the logic as follows:

if (alreadyExistingUser) {
    return res.status(400).json({
        message: "Username or email is in use",
        result: false,
    });
}

Answer №2

give this a shot!

const checkUsername = await User.findOne({ username: userData.username });
  if (checkUsername){
    return res.status(400).send("Username is already taken")
  }

const checkEmail = await User.findOne({ email: userData.email});
 if (checkEmail ){
    return res.status(400).send("Email is already in use")
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to import a geojson file into Express.js?

I'm currently trying to read a geojson file in Node.js/express.js. The file I am working with is named "output.geojson". I want to avoid using JSON.parse and instead load it using express.js (or at least render it as JSON within this function). var o ...

Using Express and Sequelize: Implementing foreign key assignment in a POST route

My goal is to handle a post request at /api/routines, which will trigger the creation of a new entry in the routines table while setting the userId foreign key to match the current user. The snippet below showcases my Routine model: const Routine = db.def ...

Error: The function "navigate" has not been declared or defined

Just starting out in reactjs and embarking on a new project. I've successfully implemented a register and login function using firebase, but hit a snag when trying to navigate to a new page like the dashboard upon user login, I encountered this error: ...

Axios is repeatedly making GET requests to an incorrect endpoint

I have set up axios to make requests to my express backend hosted on localhost:8081 src/htpp/index.js import axios from 'axios' export default axios.create({ baseURL: 'http://localhost:8081/api/', timeout: 1000, headers: {&apos ...

Can a JavaScript object be created in TypeScript?

Looking for a way to utilize an existing JavaScript "class" within an Angular2 component written in TypeScript? The class is currently defined as follows: function Person(name, age) { this.name = name; this.age = age; } Despite the fact that Java ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

No content displaying after deploying React/Node app on Replit or Heroku

Currently, I am developing an ecommerce service using React and NodeJS/Express. While I have successfully deployed my project on Replit, I am facing an issue where it only works on my local server. On other devices, the screen remains blank. I suspect that ...

Tips for detecting a new day with server-side JavaScript

I am currently developing a website that includes a schedule for teachers. I have encountered the need to delete elapsed days data from a database. What is the most effective method to monitor when it is exactly 12 midnight? If I were to use setInterval( ...

Encountering an issue with undefined property 'path' while attempting to upload an image on the frontend in React

I have encountered an issue while trying to upload an image on the frontend. The error message displayed is: message: "Cannot read property 'path' of undefined" status: "fail" When I log req.file on the backend and attempt to ...

Tips for updating a specific field in a document with Mongoose

I am utilizing the following code snippet to update a document in MongoDB and it is working perfectly: db.hs.update( {username: "hraj3116", "event_movie.name": "h"}, {$set:{"event_movie.$.theatre":"vikas mall"} }) Now, I am looking to ach ...

The color of the progress bar in JS is not displaying properly

My work involves using jQuery to manipulate progress bars. The issue I am facing is defining standard colors that should be displayed on the progress bar based on the value received. Here is my code: var defaultSegmentColors = ['#FF6363', &ap ...

Using jQuery to update a specific item in a list

My current project involves developing an Image Gallery app. It uses <img> tags within li elements. The code snippet is as follows: var $slideR_wrap = $(".slideRoller_wrapper"); var $slidesRoller = $slideR_wrap.find(".slidesRoller"); var $slideR ...

Express backend data is not being shown in React

I am endeavoring to retrieve information from a postgres database and exhibit it in a table. server.js require("dotenv").config(); const cors = require("cors") const db = require("./db"); // Express Applicatio ...

Before displaying the rows stored in the controller, ng-repeat initially displays one row

I am experiencing an issue with my back end service sending data to a $scope variable. I am using this variable to populate rows in a table with ng-repeat. Upon loading the page, initially one row is visible on the browser but then disappears once the loa ...

Concurrent Accordion and Color Transformation Animations

I am currently utilizing jQuery version 2.0.3 and jQuery UI version 1.10.3, specifically using the accordion feature. I am attempting to modify the color of the accordion panels as they open and close by implementing the following code: $(".main-content") ...

What is the best way to integrate Halfmoon's JS from npm into my current code using Gulp?

I am eager to incorporate the Halfmoon framework into a personal project and have successfully downloaded it through npm. To utilize the example JavaScript provided on this page (found at ), I need to import the library using a require statement. var halfm ...

I am attempting to access an Angular variable using JavaScript, but unfortunately, I am encountering some issues

I'm currently implementing the following code: window.onload=function(){ var dom_el2 = document.querySelector('[ng-controller="myCtrl"]'); var ng_el2 = angular.element(dom_el2); var ng_el_scope2 = ng_el2.scope(); console.log ...

js - displaying function results in an HTML table

I have developed a tool that can display the repayment schedule over the loan term. I have successfully calculated the monthly payment, interest, and remaining loan amount, but I am facing difficulty in presenting this data in a table format. I aim to hav ...

Transfer information using AJAX and JSON in JavaScript to send data to the server and fetch information from the server

I am delving into the world of AJAX and JSON for the first time. I stumbled upon some code on this site and made some modifications: send json object from javascript to php My goal is to send dynamic data (variables, arrays, etc.) in JavaScript, allowing ...

Use JWT to log out securely

Recently, I've been delving into developing an authentication system using Mongoose (which is new to me), and I'm seeking feedback on my methodology for managing JWT token expiration during user logout. I've devised a scheme that involves c ...