loading...

Simple Login With Node.js, Express, and MySQL

jeremiahiro profile image JEREMIAH IRO Updated on ・3 min read

Login With Node.js, Express, and MySQL

Prerequisite

  • Express - npm install express
  • Express Sessions - npm install express-session
  • MySQL Server
  • MySQL for Node.js - npm install MySQL
  • Node.js

Lets Get Started

First, create a folder called auth cd into the folder and run the following command on your terminal
npm init
On the prompt type login and on the prompt for entry point type login.js.

Afterward, the prerequisite packages will be installed

npm install express
npm install express-session
npm install MySQL

Create Login Function

In your login.js, you need to include the following packages

var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');

DB Connection

You can run the following in your console or using your preferred MySQL

CREATE DATABASE IF NOT EXISTS `auth` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE auth;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO users (`id`, `username`, `password`, `email`) VALUES (1, 'jeremiahiro', 'password1', 'jeremiahiro@gmail.com');

ALTER TABLE 'accounts' ADD PRIMARY KEY ('id');
ALTER TABLE 'accounts' MODIFY 'id' int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

This will create a database with the name auth and the table users and also insert test credentials.

Next up we will try to connect to the database using the following commands.

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'auth'
});

We would use Express which was installed earlier, this is because it includes packages that will help in sessions and handling HTTP requests

var app = express();

app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());

N/B: change the secret code for the sessions as the sessions will be used to determine if a user is logged in or not.

The bodyParser is used to extract data from the login form.

To display our login form we use the following

app.get('/', function(request, response) {
    response.sendFile(path.join(__dirname + '/login.html'));
});

I'm assuming you have a beautifully styled form named login.html

To handle the POST request form the login form action should be /login.

// for action
app.post('/login', function(request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if (username && password) {
// check if user exists
        connection.query('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
            if (results.length > 0) {
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('/home');
            } else {
                response.send('Incorrect Username and/or Password!');
            }           
            response.end();
        });
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
});

One the user is authenticated, we can not redirect to our application home page or dashboard

app.get('/dashboard', function(request, response) {
    if (request.session.loggedin) {
        response.send('Welcome back, ' + request.session.username + '!');
    } else {
        response.send('Please login to view this page!');
    }
    response.end();
});

For testing our application, it needs to listen to a port at such we will use port 3000

app.listen(3000);

That's all we need to create a basic login.

Posted on by:

jeremiahiro profile

JEREMIAH IRO

@jeremiahiro

Business Management Graduate Turned Web Developer

Discussion

pic
Editor guide