0
0
Expressframework~5 mins

Why authentication matters in Express

Choose your learning style9 modes available
Introduction

Authentication helps confirm who a user is. It keeps your app safe by letting only the right people in.

When you want users to log in to access their personal data.
When you need to protect sensitive information from strangers.
When you want to track user actions securely.
When you want to offer personalized experiences based on user identity.
Syntax
Express
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  // Check user credentials
  if (username === 'user' && password === 'pass') {
    res.send('Login successful');
  } else {
    res.status(401).send('Unauthorized');
  }
});
This example shows a simple login route in Express.
In real apps, passwords should be hashed and checked securely.
Examples
This example checks if the user is 'admin' with password '1234'.
Express
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  if (username === 'admin' && password === '1234') {
    res.send('Welcome admin!');
  } else {
    res.status(401).send('Access denied');
  }
});
This example shows protecting a route so only logged-in users can see it.
Express
app.get('/profile', (req, res) => {
  if (req.isAuthenticated()) {
    res.send('User profile page');
  } else {
    res.status(401).send('Please log in');
  }
});
Sample Program

This small Express app lets users send their username and password to log in. It checks if the user exists and replies accordingly.

Express
import express from 'express';
const app = express();
app.use(express.json());

const users = [{ username: 'user', password: 'pass' }];

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);
  if (user) {
    res.send('Login successful');
  } else {
    res.status(401).send('Unauthorized');
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Never store passwords as plain text in real apps; always hash them.

Authentication is the first step to keep your app safe and private.

Summary

Authentication confirms who a user is.

It protects your app from unauthorized access.

Use it whenever you want to keep data or features private.