Express: Student Login Page
Create a student portal login system using Express.js.
Create a /register route to add a new student with a
rollNo,name, andpassword.Use
express-sessionto store the session data after a successful login from the /login route.Upon successful login, also set a cookie named
studentPortalAccesswith the student'srollNoand an expiry time of 3 minutes.Properly configure and use middleware (
cookie-parserandexpress-session) to manage cookies and sessions throughout the application.
Template
A Basic Skeleton Implementation based on Question
import express from 'express';
const app = express();
const PORT = 3000;
app.use(express.json());
import session from 'express-session';
app.use(session({
secret: 'Any-String-as-Secret',
resave: false,
saveUninitialized: false,
cookie: {secure: false}
}))
import cookieParser from 'cookie-parser';
app.use(cookieParser());
const students = [];
app.post('/register', (req, res)=>{
// add new student with rollNo, name, password
});
app.post('/login', (req, res)=>{
// set studentPortalAccess cookie with rollno, 3min
})
app.listen(PORT, ()=>{
console.log(`Students can register at ${PORT}`);
})app.js
Implementation with filled data
import express from 'express';
import session from 'express-session';
import cookieParser from 'cookie-parser';
// --- App Initialization ---
const app = express();
const PORT = 3001;
// --- In-Memory Storage (for demonstration) ---
const students = [];
// --- Middleware ---
// Parse incoming JSON requests
app.use(express.json());
// Parse cookies from the request headers
app.use(cookieParser());
// Initialize session management
app.use(session({
secret: 'student-secret-key',
// Secret key for signing the session ID cookie
resave: false,
// Don't save session if unmodified
saveUninitialized: false,
// Don't create session until something is stored
cookie: { secure: false }
// In production, set to true for HTTPS
}));
// --- API Routes ---
app.post('/register', (req, res) => {
const { rollNo, name, password } = req.body;
if (!rollNo || !name || !password) {
return res.status(400).send('All fields are required.');
}
// could have used find() or findIndex()
if (students.some(s => s.rollNo === rollNo)) {
return res.status(409).send('Student with this roll number is already registered.');
}
let newStudent = { rollNo, name, password}
students.push( newStudent );
console.log('Current students:', students);
res.status(201).send('Registered successfully!');
});
app.post('/login', (req, res) => {
const { rollNo, password } = req.body;
const student = students.find(s => s.rollNo === rollNo && s.password === password);
if (!student) {
return res.status(401).send('Invalid credentials.');
}
// Store student data in the session
req.session.student = student;
// Set a cookie for 3 minutes
res.cookie( 'studentPortalAccess',
student.rollNo,
{ maxAge: 3 * 60 * 1000 });
res.send(`Welcome, ${student.name}!`);
});
app.get('/result', (req, res) => {
// Check if a student session exists
if (!req.session.student) {
return res.status(401).send('Access denied. Please log in first.');
}
res.send(`Hi ${req.session.student.name}, your results are available!`);
});
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.status(500).send('Could not log out.');
}
res.clearCookie('studentPortalAccess');
res.send('Logged out successfully.');
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});With Form Submission through ejs
Directory Structure
/student-portal
├── views/
│ ├── register.ejs
│ ├── login.ejs
│ └── dashboard.ejs
├── app.js
└── package.jsonapp.js
This file sets up the Express server, configures middleware for sessions and cookies, and defines the routes for registration, login, the dashboard, and logout.
import express from 'express';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import path from 'path';
import { fileURLToPath } from 'url';
const app = express();
const PORT = 3000;
// Needed for __dirname in ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// --- Middleware Setup ---
app.use(express.urlencoded({ extended: true })); // To parse form data
app.use(cookieParser()); // To parse cookies
app.use(session({
secret: 'a_secret_key_to_sign_the_cookie', // Replace with a real secret
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Set to true if using HTTPS
}));
// Set EJS as the view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// In-memory student database
const students = [];
// --- Routes ---
// Render registration page
app.get('/register', (req, res) => {
res.render('register');
});
// Handle registration logic
app.post('/register', (req, res) => {
const { rollNo, name, password } = req.body;
students.push({ rollNo, name, password });
console.log('Students:', students);
res.redirect('/login');
});
// Render login page
app.get('/login', (req, res) => {
res.render('login');
});
// Handle login logic
app.post('/login', (req, res) => {
const { rollNo, password } = req.body;
const student = students.find(s => s.rollNo === rollNo && s.password === password);
if (student) {
// Create session
req.session.student = { rollNo: student.rollNo, name: student.name };
// Set cookie with 3-minute expiry
res.cookie('studentPortalAccess', student.rollNo, {
maxAge: 3 * 60 * 1000 // 3 minutes in milliseconds
});
res.redirect('/dashboard');
} else {
res.send('Invalid roll number or password.');
}
});
// Render dashboard (protected route)
app.get('/dashboard', (req, res) => {
if (req.session.student) {
res.render('dashboard', { student: req.session.student });
} else {
res.redirect('/login');
}
});
// Handle logout
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.redirect('/dashboard');
}
res.clearCookie('studentPortalAccess');
res.redirect('/login');
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}/register`);
});EJS Files
views/register.ejs
<!DOCTYPE html>
<html lang="en">
<head><title>Register</title></head>
<body>
<h1>Student Registration</h1>
<form action="/register" method="POST">
<input type="text" name="rollNo" placeholder="Roll Number" required><br><br>
<input type="text" name="name" placeholder="Full Name" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<button type="submit">Register</button>
</form>
</body>
</html>views/login.ejs
<!DOCTYPE html>
<html lang="en">
<head><title>Login</title></head>
<body>
<h1>Student Login</h1>
<form action="/login" method="POST">
<input type="text" name="rollNo" placeholder="Roll Number" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<button type="submit">Login</button>
</form>
<p>Don't have an account? <a href="/register">Register here</a>.</p>
</body>
</html>views/dashboard.ejs
<!DOCTYPE html>
<html lang="en">
<head><title>Dashboard</title></head>
<body>
<h1>Welcome to the Student Portal, <%= student.name %>!</h1>
<p>Your Roll Number is: <%= student.rollNo %></p>
<a href="/logout">Logout</a>
</body>
</html>Run and Test
npm init -y
npm install express express-session cookie-parser ejsThen, ensure your package.json includes "type": "module".
node app.jsNavigate to
http://localhost:3000/registerto create a new student account.After registering, you will be redirected to the login page. Log in with the credentials you just created.
Upon successful login, you will be taken to the dashboard.
Open your browser's developer tools and inspect the cookies for the site. You will see two cookies:
connect.sid: The session cookie managed byexpress-session.studentPortalAccess: The custom cookie you set, containing the student's roll number and set to expire in 3 minutes.
Try to access
http://localhost:3000/dashboardin a new private/incognito browser window. You will be redirected to the login page because no session exists.Click the "Logout" link on the dashboard to destroy the session and clear the cookie. You will be redirected to the login page.
