User Registration in Node.js
Learn how to register new users, validate their information, hash passwords, and save user accounts in a MySQL database using Node.js and Express.js.
User registration allows new users to create accounts in an application. During registration, the server receives user information, validates the submitted data, hashes the password, and saves the account in the database.
In this tutorial, we will create a registration API using Express.js, bcrypt, and mysql2. We will also learn how to handle duplicate email addresses and return appropriate HTTP responses.
1. What Is User Registration?
User registration is the process through which a new user creates an account by providing information such as a name, email address, and password.
The server validates the submitted information and stores the user's account details in a database. The password should never be stored as plain text.
2. How User Registration Works
A typical registration workflow follows these steps:
Name, email, and password
Receives the request and validates the input
Check whether the email is already registered
Generate a secure password hash using bcrypt
Insert the account into the database
Return a registration success message
3. Install Required Packages
Create a Node.js project if you do not already have one. Install Express.js, bcrypt, and mysql2.
npm init -y
npm install express bcrypt mysql2 dotenv
These packages provide the following functionality:
| Package | Purpose |
|---|---|
express |
Creates the API and handles HTTP requests. |
bcrypt |
Hashes passwords and verifies submitted passwords. |
mysql2 |
Connects Node.js to MySQL. |
dotenv |
Loads configuration from environment variables. |
4. Create the Users Table
Before registering users, create a database table to store their names, email addresses, and password hashes.
CREATE DATABASE auth_demo;
USE auth_demo;
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The email column has a UNIQUE constraint. This prevents two accounts from being created with the same email address, even if two registration requests arrive at nearly the same time.
password_hash column stores the bcrypt hash,
not the original password.
5. Configure the Database Connection
Create a file named db.js and configure a MySQL
connection pool.
require("dotenv").config();
const mysql = require("mysql2/promise");
const pool = mysql.createPool({
host: process.env.DB_HOST || "localhost",
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || "auth_demo",
waitForConnections: true,
connectionLimit: 10
});
module.exports = pool;
Create a .env file for local development:
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=YOUR_MYSQL_PASSWORD
DB_NAME=auth_demo
PORT=3000
Replace the placeholder with your MySQL password. Keep the
.env file out of source control and never commit
actual credentials.
6. Create the User Registration API
Create a file named server.js. The following
endpoint validates the submitted details, checks for an existing
email, hashes the password, and inserts the new account.
require("dotenv").config();
const express = require("express");
const bcrypt = require("bcrypt");
const pool = require("./db");
const app = express();
app.use(express.json());
app.post("/api/auth/register", async (req, res) => {
try {
const { name, email, password } = req.body;
if (
typeof name !== "string" ||
typeof email !== "string" ||
typeof password !== "string"
) {
return res.status(400).json({
message: "Name, email, and password are required."
});
}
const normalizedName = name.trim();
const normalizedEmail = email.trim().toLowerCase();
if (
normalizedName.length < 2 ||
normalizedName.length > 100
) {
return res.status(400).json({
message: "Name must contain between 2 and 100 characters."
});
}
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (
normalizedEmail.length > 255 ||
!emailPattern.test(normalizedEmail)
) {
return res.status(400).json({
message: "Please provide a valid email address."
});
}
if (
password.length < 12 ||
Buffer.byteLength(password, "utf8") > 72
) {
return res.status(400).json({
message:
"Password must be at least 12 characters and no more than 72 UTF-8 bytes."
});
}
const [existingUsers] = await pool.execute(
"SELECT id FROM users WHERE email = ?",
[normalizedEmail]
);
if (existingUsers.length > 0) {
return res.status(409).json({
message: "An account with this email already exists."
});
}
const passwordHash = await bcrypt.hash(password, 12);
await pool.execute(
`INSERT INTO users (name, email, password_hash)
VALUES (?, ?, ?)`,
[normalizedName, normalizedEmail, passwordHash]
);
return res.status(201).json({
message: "User registered successfully."
});
} catch (error) {
if (error.code === "ER_DUP_ENTRY") {
return res.status(409).json({
message: "An account with this email already exists."
});
}
console.error("Registration failed:", error.message);
return res.status(500).json({
message: "Unable to register user."
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
The code checks for an existing email before inserting the account. The database's UNIQUE constraint provides the final protection against duplicate email addresses.
7. Test User Registration Using Postman
Start the server and send a POST request to the registration endpoint.
node server.js
Request method: POST
http://localhost:3000/api/auth/register
In Postman, select Body → raw → JSON and send the following data.
{
"name": "Rahul Sharma",
"email": "rahul@example.com",
"password": "MyStrongPassword123!"
}
Successful response:
{
"message": "User registered successfully."
}
The server returns HTTP status 201 Created
when the user is successfully registered.
8. Handle Duplicate Email Addresses
If the user submits an email address that already exists, the API should not create a second account using that address.
For example, if rahul@example.com has already been
registered, another registration request using the same email
should receive a conflict response.
{
"message": "An account with this email already exists."
}
The response uses HTTP status 409 Conflict.
In some public-facing systems, a generic response may be preferable
to avoid revealing whether a particular email address is registered.
9. Common Registration Errors
| Status Code | Meaning | Example |
|---|---|---|
| 201 | Created | User registered successfully. |
| 400 | Bad Request | Missing or invalid input. |
| 409 | Conflict | Email address already exists. |
| 500 | Internal Server Error | Unexpected database or server error. |
10. User Registration Flow
Collect name, email, and password
Check required fields and input formats
Check existing accounts and enforce uniqueness
Generate a bcrypt password hash
Save the new account with its password hash
Confirm that registration succeeded
Important Points to Remember
- User registration creates a new account.
- Validate all user input on the server.
- Normalize email addresses consistently.
- Use a UNIQUE database constraint for email addresses.
- Never store passwords as plain text.
- Hash passwords using bcrypt or another suitable password-hashing algorithm.
- Use parameterized SQL queries.
- Return appropriate HTTP status codes.
- Keep database credentials in environment variables.
- Never return password hashes in API responses.
Summary
User registration allows new users to create accounts in an application. We created a registration API using Express.js, bcrypt, and MySQL, including input validation, duplicate email handling, password hashing, and database insertion.
In the next tutorial, we will learn how to authenticate registered users through a secure login process.