Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Created November 6, 2023 21:33
Show Gist options
  • Save EteimZ/b9525cd6c6d05d51fa7e0425c4b76bbe to your computer and use it in GitHub Desktop.
Save EteimZ/b9525cd6c6d05d51fa7e0425c4b76bbe to your computer and use it in GitHub Desktop.
Cookie based Authentication in vanilla node js
const http = require('http');
const fs = require('fs');
const url = require('url');
// Simulated user data
const users = [
{ id: 1, username: 'john_doe', password: 'password123' },
{ id: 2, username: 'jane_smith', password: 'example456' }
];
const sessions = {};
function setSession(userId, res) {
const sessionId = `session_${new Date().getTime()}`;
sessions[sessionId] = userId;
// Set the session ID as a cookie
res.setHeader('Set-Cookie', `sessionId=${sessionId}; HttpOnly; Path=/`);
}
function handleLogin(req, res) {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const requestData = body.split('&').reduce((acc, curr) => {
const [key, value] = curr.split('=');
acc[key] = value;
return acc;
}, {});
const { username, password } = requestData;
const user = users.find(user => user.username === username && user.password === password);
if (user) {
setSession(user.id, res);
res.writeHead(302, { 'Location': '/protected' });
res.end();
} else {
res.writeHead(401, { 'Content-Type': 'text/plain' });
res.end('Invalid username or password');
}
});
}
function handleLoginGet(req, res) {
fs.readFile('login.html', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
}
function handleProtectedRoute(req, res) {
// Get the session ID from the cookie
const cookie = req.headers.cookie;
if (cookie && cookie.startsWith('sessionId=')) {
const sessionId = cookie.split('=')[1];
if (sessions[sessionId]) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the protected route!');
} else {
res.writeHead(401, { 'Content-Type': 'text/plain' });
res.end('Unauthorized access');
}
} else {
res.writeHead(401, { 'Content-Type': 'text/plain' });
res.end('Unauthorized access');
}
}
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
if (req.method === 'GET' && parsedUrl.pathname === '/login') {
handleLoginGet(req, res);
} else if (req.method === 'POST' && parsedUrl.pathname === '/login') {
handleLogin(req, res);
} else if (req.method === 'GET' && parsedUrl.pathname === '/protected') {
handleProtectedRoute(req, res);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page not found');
}
});
const PORT = 3002;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
@alissonmarcs
Copy link

so awesome!
this help me so much, many thanks

@EteimZ
Copy link
Author

EteimZ commented Jul 10, 2025

@alissonmarcs I am so glad it could be of help to you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment