Loading

Quipoin Menu

Learn • Practice • Grow

express-js / ExpressJS Authentication Basics
tutorial

ExpressJS Authentication Basics

Imagine you're at an airport. Before you can board a flight, you need to show your passport and ticket to prove who you are. This is authentication proving your identity. In web applications, authentication is the process of verifying that users are who they claim to be.

What is Authentication?

Authentication is the process of confirming a user's identity. It answers the question: "Who are you?" The most common way is through username/email and password. Once authenticated, the server knows who the user is and can provide personalized experiences.

Authentication vs Authorization

  • Authentication Who are you? (Identity verification)
  • Authorization What are you allowed to do? (Permissions)
For example, logging into a website is authentication. Being able to access the admin panel is authorization.

How Authentication Works in Express

A typical authentication flow in Express:
  1. User submits login form with email and password (POST request).
  2. Server checks if user exists in database and verifies password.
  3. If valid, server creates a session or token to remember the user.
  4. Server sends this session/token back to client (via cookie or JSON).
  5. On subsequent requests, client sends this credential, and server verifies it.

Simple Authentication Example (with hardcoded user)
const express = require('express');
const app = express();

app.use(express.json());

// Mock database
const users = [
{ id: 1, email: 'user@example.com', password: 'secret123' }
];

// Login endpoint
app.post('/login', (req, res) => {
const { email, password } = req.body;

// Find user by email
const user = users.find(u => u.email === email);

// Check if user exists and password matches
if (user && user.password === password) {
// In real apps, you'd create a session/token here
res.json({
success: true,
message: 'Login successful',
userId: user.id
});
} else {
res.status(401).json({
success: false,
message: 'Invalid credentials'
});
}
});

Password Hashing Never Store Plain Passwords!

Storing passwords in plain text is extremely dangerous. Always hash passwords using libraries like bcrypt.
npm install bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 10;

// Hash a password before storing
const hashPassword = async (plainPassword) => {
const hash = await bcrypt.hash(plainPassword, saltRounds);
return hash;
};

// Compare password with hash during login
const comparePassword = async (plainPassword, hash) => {
const match = await bcrypt.compare(plainPassword, hash);
return match;
};

Session-Based Authentication

Using express-session for session-based authentication (we covered this in Group 4).
const session = require('express-session');

app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24 * 60 * 60 * 1000 } // 24 hours
}));

app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });

if (user && await bcrypt.compare(password, user.password)) {
// Store user info in session
req.session.userId = user.id;
req.session.userEmail = user.email;
res.json({ success: true, message: 'Logged in' });
} else {
res.status(401).json({ success: false, message: 'Invalid credentials' });
}
});

// Protected route
app.get('/dashboard', (req, res) => {
if (!req.session.userId) {
return res.status(401).json({ error: 'Please log in' });
}
res.json({ message: `Welcome user ${req.session.userId}` });
});

// Logout
app.post('/logout', (req, res) => {
req.session.destroy();
res.json({ message: 'Logged out' });
});

Two Minute Drill
  • Authentication verifies who a user is; authorization determines what they can do.
  • Never store plain text passwords always hash them with bcrypt.
  • Session-based authentication uses server-side storage and cookies.
  • Token-based authentication (JWT) is stateless and popular for APIs.
  • Always validate user input and handle errors gracefully.

Need more clarification?

Drop us an email at career@quipoinfotech.com