Implementing User Authentication in Express Apps
User authentication is the process of verifying the identity of a user attempting to gain access to your application. It involves authorizing and transferring credentials to confirm a user’s authenticity.
Sign up forfree
Forgot your password?
Create an account
*Required: 8 chars, 1 capital letter, 1 number
By continuing, you agree to thePrivacy PolicyandTerms of Use.You also agree to receive our newsletters, you can opt-out any time.

Step 1: Setting Up Development Environment
First, create a project folder andcdinto it by running:
Next, initialize npm in your project directory by running:

The-yflag initializes npm and creates yourpackage.jsonfile with all its defaults.
This user authentication model requires a few dependencies.

They include:
Install the packages by running:

Next, create anapp.jsfile in your project’s root directory and add the code block below to create a basic Express server:
This code creates an express application instance by calling the express function. It then uses thebody-parsermiddleware to parse incoming request bodies. Then it starts listening for traffic on port 3000 by calling the express instance’s listen method and passing the port variable as an argument.

Step 2: Connecting Your Application to a Database
In your project’s root directory, create a.envfile and store your MongoDB credentials in it. This avoids exposing your database credentials in code which can give malicious users access to your database.
Next, navigate to yourapp.jsfile and import mongoose:
Then, call importdotenvand call theconfigmethod on it:
Calling theconfigmethod ondotenvloads environmental variables into theprocess.env.
Finally, call the connect method onmongooseand pass your MongoDB URI as an argument:
Step 3: Creating User Model
In your project’s root directory, create a “models” folder; this is where you will store your mongoose model:
Next, create a “userModel” file and add the following imports:
isEmailis a validation function that returnstrueif a given string is an email. You will need it to apply mongoose validation to your user model.
Next, add the following code to youruserModelfile:
The code above creates auserSchemavariable that stores the value of themongoose.Schemamethod. The mongoose.Schema method maps properties to a MongoDB collection and defines the shape of the documents within it. The mongoose schema has two properties—anemailand apassword—which will be your authentication requirements.
The email property is a string type and hasrequiredset to true. The accompanying error message, “Email is required,” will display if a request body does not contain anemailproperty. Finally, using mongoose custom validation, thevalidatorproperty referenes theisEmailfunction. That function returns true or false based on the validity of the string as an email. Then the message property takes the email value (props) and constructs a meaningful error message.
The password property is a required string type with an error message that reads “Password is required”. Thevalidatorfunction is an anoymous one that returns true if the password is at least six characters long.
The final line creates and exports a mongoose model by calling themodelmethod onmongoose.Pass the model name (User) as the first argument and a schema (userSchema) as the second argument.
Step 4: Implementing Sign-in and Sign-up Routes
In your project’s root directory, create aroutesfolder:
In your routes folder, create auserRoutes.jsfile and add the following imports:
Create an Express Router instance by calling theRoutermethod onexpress:
Next, create your sign-up route by adding the code block below to youruserRoute.jsfile:
In the code block above, first, you de-structured the email and password from thereq.bodyobject. Then, check if a user is already using the email because it should be unique for each user. If the email has already been used, you return and stop code execution with a 401 status code.
Storing plain passwords in a database is a huge security threat as malicious hackers might gain access to the database. You should hash passwords before sotring them in your database, so even if a hacker discovers them, there shouldn’t be a risk to users. Hashing is the process of converting a given “key” into another value. Hashing is a one-way function, which means that you cannot retrieve the original value from the hased one, unlike encryption.
Using bcrypt, you hashedyour user password by calling the hash method on bcrypt. The hash method takes three parameters: the string to be hashed, salt rounds, and a callback function. You pass the user password, the saltRounds variable you created earlier, and a callback.
Salt rounds refer to the time needed to calculate a single bcrypt hash. The higher the salt rounds, the more the hashing rounds.
If the hash method throws an error, you throw an “internal server error.” Else, you set the password property to the successful hash and save it to your database by calling the save method on theUserinstance.
Next, create your sign-in route by adding the code block below to youruserRoute.jsfile:
In the code block above, first, you de-structure the email and password from thereq.bodyobject. Then, you check if a user exists in your database. If the user doesn’t exist in your database, you return with a 401 status code.
Next, using bcrypt’s compare method, pass in the password the user provided and the hashed password you retrieved from your database. Compare the two to confirm if they match. If the passwords match, you return a 200 status code and a success message. Else you return a 401 status code and an error message.
Finally, importrouterinto yourapp.jsfile and use it as an application-level middleware.
This completes your user authentication model; now, users can securely sign-up and sign in to your application.
The Importance of User Authentication
User authentication ensures that only legitimate users can gain access to your application. If your data is in any way personal or private, you should take steps to preventing unauthenticated users from gaining access.
User authentication is crucial for protecting sensitive information. Luckily, it’s not difficult to implement this.
You don’t need to fork out for expensive hardware to run an AI on your PC.
The best features aren’t the ones being advertised.
Quality apps that don’t cost anything.
Turn these settings on, and your iPhone will be so much better than before.
So much time invested, and for what?