How To Validate Username And Password In Javascript From Database

Connecting to the Databaseill learn how to validate a username and password in JavaScript using a database. We will use the popular web development stack, Node.js, Express.js, and MySQL, to implement a simple login system.

Prerequisites

Before we start, make sure that you have the following installed on your system:

  • Node.js and npm
  • MySQL Server

Setting up the Project

First, let’s set up a new Node.js project. Open your terminal and run the following commands:

mkdir login-system
cd login-system
npm init -y
    

This will create a new directory called login-system and initialize an empty Node.js project inside it.

Installing Dependencies

Next, we need to install the necessary dependencies for our project. We will be using Express.js for our server, MySQL for the database connection, and body-parser to parse the incoming request data. Install these dependencies by running:

npm install express mysql body-parser
    

Creating the Database

Now let’s create a MySQL database and a table to store our user credentials. Open MySQL prompt and run the following commands:

CREATE DATABASE login_db;
USE login_db;
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
);
    

Connecting to the Database

Let’s create a new file called database.js inside our project directory. Here, we will set up the MySQL connection:

const mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'your_password',
    database: 'login_db'
});

connection.connect((err) => {
    if (err) throw err;
    console.log('Connected to the database.');
});

module.exports = connection;

Creating the Server

Create a new file called app.js for our main application. Import the required modules and set up the Express.js server:

const express = require('express');
const bodyParser = require('body-parser');
const database = require('./database');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', (req, res) => {
    // Login logic will go here
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Validating Username and Password

Finally, let’s write the login logic inside the app.post('/login') handler. We will query the database to see if the submitted username and password match any existing user:

app.post('/login', (req, res) => {
    const { username, password } = req.body;

    const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
    database.query(query, [username, password], (err, results) => {
        if (err) throw err;

        if (results.length > 0) {
            res.send('Logged in successfully.');
        } else {
            res.send('Invalid username or password.');
        }
    });
});

Testing the Login System

Start your server by running node app.js in your terminal. Then, test the login system by sending a POST request to http://localhost:3000/login with the username and password parameters using a tool like Postman or CURL.

Conclusion

In this blog post, we learned how to validate a username and password in JavaScript using a MySQL database. This is just a simple example, and you can further enhance the security and functionality of your login system by adding features like password hashing, input validation, and user registration.