User Authentication in Express.js (Part 1): Setting Up a Registration Route with MVC for Beginners
I'm a full-stack software engineer with a passion for building software solutions and sharing my Knowledge.
Figuring a lot of things out. These are my personal notes on my tech exploit. As I learn, I share.
When I'm not providing web services, I love providing guidance and mentorship to newbies starting their careers in tech.
Let's have a conversation.
This guide will walk you through setting up a basic Express.js server with a /register endpoint to handle user registration, using express, dotenv, and bcrypt for password hashing.
🔧 Step 1: Configure the Server
Initialize npm:
npm init -y
Install Dependencies:
npm install express dotenv bcrypt
npm install --save-dev nodemon
🖥️ Step 2: Setup server.js
require('dotenv').config();
const app = require('./app');
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
🧠 Step 3: Setup app.js
const express = require("express");
const authRoutes = require('./routes/authRoutes');
const app = express();
// Middleware
app.use(express.json());
// Test Route
app.get("/", (req, res) => {
res.send("API is Working!");
});
// Auth Routes
app.use('/api/auth', authRoutes);
module.exports = app;
📂 Step 4: Create Folders and Files
controllers/authController.jsroutes/authRoutes.js
🛠️ Step 5: Setup authRoutes.js
const express = require("express");
const router = express.Router();
const controller = require("../controllers/authController");
// Register User Route
router.post("/register", controller.registerUser);
module.exports = router;
🔐 Step 6: Setup registerUser in authController.js
const bcrypt = require('bcrypt');
exports.registerUser = async (req, res) => {
const { username, email, password } = req.body;
try {
if (!username || !email || !password) {
return res.status(400).json({ message: 'All fields are required' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const userData = {
id: Date.now(),
username,
email,
// hashedPassword: hashedPassword // optionally include this
};
res.status(201).json({ message: 'User registered successfully', user: userData });
} catch (err) {
res.status(500).json({ message: err.message });
}
};
Testing the Application
Using Postman
Register a user:
Endpoint:
POST /api/auth/registerBody:
{
"username": "john_doe",
"email": "john@example.com",
"password": "123456"
}
✅ Conclusion
In this first part of our user authentication series, you learned how to set up a basic registration route in Express.js using the MVC (Model-View-Controller) pattern. We walked through organizing your project, creating a User model, building a registration controller, and defining a route to handle incoming user data.
This foundational setup will help keep your code clean, modular, and scalable as we move forward.
In the next part of the series, we’ll implement the login functionality, where users can log in with their credentials and access protected parts of your application.
👉 What’s Next?
Stay tuned for Part 2, where we’ll:
Create a login route
Verify user credentials
Discuss basic authentication logic