Introduction
When it comes to building web applications, user authentication is one of the most important features. Without it, users cannot create accounts, access personalized content, or interact with other users. In this tutorial, we will show you how to create a registration and login form in Node.js and Postgresql.
Prerequisites
Before we get started, you will need to have some basic knowledge of Node.js, Postgresql, and HTML. You will also need to have Node.js and Postgresql installed on your computer.
Step 1: Setting up the Database
The first step is to create a database in Postgresql to store user information. You can do this by opening the Postgresql command line and typing:
createdb mydatabase
Next, create a table to store user information:
CREATE TABLE users (id SERIAL PRIMARY KEY, username VARCHAR(50), email VARCHAR(50), password VARCHAR(100));
Step 2: Setting up the Node.js Project
Next, create a new folder for your project and navigate to it in the command line. Initialize a new Node.js project:
npm init
Install the necessary packages:
npm install express pg bcrypt body-parser express-session
Create a new file called index.js and require the necessary packages:
const express = require('express'); const pg = require('pg'); const bcrypt = require('bcrypt'); const bodyParser = require('body-parser'); const session = require('express-session');
Step 3: Creating the Registration Form
Create a new file called register.html and add the following HTML code:
Step 4: Handling the Registration Form Submission
Back in index.js, add the following code to handle the registration form submission:
// Handle registration form submission app.post('/register', async (req, res) => { const { username, email, password } = req.body; const hashedPassword = await bcrypt.hash(password, 10); const client = new pg.Client(); await client.connect(); const result = await client.query('INSERT INTO users (username, email, password) VALUES ($1, $2, $3)', [username, email, hashedPassword]); await client.end(); res.send('Registration successful'); });
Step 5: Creating the Login Form
Create a new file called login.html and add the following HTML code:
Step 6: Handling the Login Form Submission
Back in index.js, add the following code to handle the login form submission:
// Handle login form submission app.post('/login', async (req, res) => { const { email, password } = req.body; const client = new pg.Client(); await client.connect(); const result = await client.query('SELECT * FROM users WHERE email = $1', [email]); await client.end(); const user = result.rows[0]; if (user && await bcrypt.compare(password, user.password)) { req.session.userId = user.id; res.send('Login successful'); } else { res.send('Invalid login credentials'); } });
Step 7: Creating the Dashboard
Create a new file called dashboard.html and add the following HTML code:
Welcome, <% username %>!
Step 8: Protecting the Dashboard
Back in index.js, add the following code to protect the dashboard so that only logged-in users can access it:
// Protect dashboard app.get('/dashboard', (req, res) => { if (req.session.userId) { res.render('dashboard.html', { username: req.session.username }); } else { res.redirect('/login'); } });
Step 9: Creating the Logout Functionality
Add the following code to index.js to handle the logout functionality:
// Handle logout app.get('/logout', (req, res) => { req.session.destroy(); res.redirect('/'); });
Step 10: Testing the Application
Start the Node.js server by running:
node index.js
Open your web browser and navigate to http://localhost:3000/register. Fill out the registration form and submit it. Then navigate to http://localhost:3000/login, fill out the login form, and submit it. You should be redirected to the dashboard page, where you can see your username and a logout button. Clicking the logout button should log you out and redirect you back to the login page.
Conclusion
Creating a registration and login form in Node.js and Postgresql is a crucial step in building a secure web application. By following the steps outlined in this tutorial, you should now have a basic understanding of how to create these forms and handle user authentication. With some additional customization, you can create a more robust authentication system that meets the needs of your specific application.