Creating a Node.js Login System

Sep 3, 2024

Building a Login System with Node and MySQL

Introduction

  • Objective: Build a login system using Node.js and MySQL.
  • Overview of the project structure:
    • Home Page
    • Login Page
    • Register Page

User Registration

  • Example User Registration:
    • Name: Max Smith
    • Email: max@email.com
    • Password: 123456
  • Upon registration, user details are stored securely in the database (passwords are hashed).

User Profile

  • Profile page accessible only to logged-in users.
  • Links available:
    • Home
    • Profile (for logged-in users)
    • Logout
  • Log out functionality:
    • Redirects to login form if user tries to access profile after logging out.

Technologies Used

Database

  • MySQL (using XAMPP or MAMP)
    • XAMPP for Windows
    • MAMP for macOS
  • Starting MySQL server:
    • Navigate to: C:\Program Files\XAMPP
    • Run xampp-control.exe and start Apache & MySQL.

Environment Setup

Code Editor

  • Using Visual Studio Code.
  • Create a new folder (e.g., node-sql) for the project.
    • Open folder in VS Code.

Initializing Node Project

  • Ensure Node.js is installed:
    • Check installation: node -v
  • Initialize project with npm init -y.
    • This creates a package.json file.

Installing Dependencies

  • Required dependencies:
    • express: Framework to start the server.
    • mysql: To connect Node.js with MySQL.
    • dotenv: To manage sensitive information.
    • hbs: For HTML templating.
    • nodemon: Automatically restarts server on changes.
      • Installation command: npm install --save nodemon
      • Use sudo for installation on macOS if errors arise.

Setting Up App.js

  • Create app.js file in the project folder.
  • Basic setup:
    • Import Express: const express = require('express');
    • Create an Express app: const app = express();
    • Define routes and server behavior:
      • Basic route for home page:
        app.get('/', (req, res) => {
            res.send('home page');
        });
        
  • Start the server:
    • Listen on a specified port (e.g., 5001):
      app.listen(5001, () => {
          console.log('Server started on port 5001');
      });
      

Configuring NPM Scripts

  • Add a start script in package.json:
    "scripts": {
        "start": "nodemon app.js"
    }
    
  • Using npm start to run the server with nodemon for live reloads.

Testing the Setup

  • Open browser and navigate to localhost:5001.
  • Verify that the home page message appears.

Conclusion

  • Successfully set up a basic Node.js project with Express and MySQL.
  • Next steps: Connect to the MySQL database and implement functionalities.