Skip to content

3. Authentication with REST API

1. ✅ Authentication with REST API

  • Backend: Express.js with express-session to manage sessions.

  • Frontend: Plain JavaScript making REST calls (fetch).

  • Session flow:

    • User logs in via a REST endpoint.
    • Server stores session data.
    • Browser stores a session cookie (connect.sid).
    • Subsequent requests reuse the session.

📦 Step 1: Install Required Packages

Terminal window
npm install express express-session cors body-parser

🖥️ Backend (server.js)

const express = require('express');
const session = require('express-session');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
// CORS for frontend on a different port (e.g., 5500)
app.use(cors({
origin: 'http://localhost:5500', // Change if your frontend is hosted elsewhere
credentials: true
}));
app.use(bodyParser.json());
// Session setup
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // Set to true if using HTTPS
httpOnly: true,
maxAge: 1000 * 60 * 60 // 1 hour
}
}));
// Fake login
app.post('/api/login', (req, res) => {
const { username } = req.body;
if (username) {
req.session.user = { username };
res.json({ message: 'Logged in', user: req.session.user });
} else {
res.status(400).json({ error: 'Username required' });
}
});
// Get session info
app.get('/api/me', (req, res) => {
if (req.session.user) {
res.json({ user: req.session.user });
} else {
res.status(401).json({ error: 'Not logged in' });
}
});
// Logout
app.post('/api/logout', (req, res) => {
req.session.destroy(() => {
res.json({ message: 'Logged out' });
});
});
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

🌐 Frontend (index.html)

<!DOCTYPE html>
<html>
<head>
<title>Session Demo</title>
</head>
<body>
<input id="username" placeholder="Username" />
<button onclick="login()">Login</button>
<button onclick="getProfile()">Get Profile</button>
<button onclick="logout()">Logout</button>
<pre id="output"></pre>
<script>
const API = 'http://localhost:3000/api';
async function login() {
const username = document.getElementById('username').value;
const res = await fetch(`${API}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // Important: send cookies
body: JSON.stringify({ username })
});
const data = await res.json();
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
}
async function getProfile() {
const res = await fetch(`${API}/me`, {
credentials: 'include'
});
const data = await res.json();
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
}
async function logout() {
const res = await fetch(`${API}/logout`, {
method: 'POST',
credentials: 'include'
});
const data = await res.json();
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
}
</script>
</body>
</html>

🔐 Important Notes

  • Cookies: express-session stores a cookie (connect.sid). The browser must send it back.
  • CORS: Make sure credentials: true is set both server-side and client-side.
  • HTTPS: If deploying with HTTPS, set cookie.secure: true.