Example : A standard & complete Dashboard with proper credentials, Login, and multiple .ejs files in Node.js.




The fully optimized EJS dashboard structure with user login using Node.js, Express, and EJS, along with route protection, sessions, and clean modular code are -

Node.Js-dashboard Structure/
│
├── views/
│   ├── partials/
│   │   ├── header.ejs
│   │   ├── footer.ejs
│   ├── dashboard.ejs
│   ├── login.ejs
│   ├── page1.ejs
│   └── page2.ejs
│
├── public/
│   └── css/
│       └── style.css
│
├── server.js
├── package.json


Step 1: Initialize and Install required Packages

mkdir NodeJs-dashboard
cd NodeJs-dashboard
npm init -y
npm install express ejs body-parser express-session


Step 2: Create server.js

const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();
const PORT = 3000;

// Middleware
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret: 'your_secret_key',
    resave: false,
    saveUninitialized: true
}));

// Mock user (replace with DB in real app)
const user = {
    username: "admin",
    password: "admin123"
};

// Auth middleware
function isAuthenticated(req, res, next) {
    if (req.session.loggedIn) {
        return next();
    }
    res.redirect('/login');
}

// Routes
app.get('/', (req, res) => res.redirect('/dashboard'));

app.get('/login', (req, res) => {
    res.render('login', { error: null });
});

app.post('/login', (req, res) => {
    const { username, password } = req.body;
    if (username === user.username && password === user.password) {
        req.session.loggedIn = true;
        req.session.username = username;
        res.redirect('/dashboard');
    } else {
        res.render('login', { error: "Invalid credentials" });
    }
});

app.get('/logout', (req, res) => {
    req.session.destroy(() => {
        res.redirect('/login');
    });
});

app.get('/dashboard', isAuthenticated, (req, res) => {
    res.render('dashboard', { username: req.session.username, title: "Dashboard" });
});

app.get('/page1', isAuthenticated, (req, res) => {
    res.render('page1', { title: "Page 1" });
});

app.get('/page2', isAuthenticated, (req, res) => {
    res.render('page2', { title: "Page 2" });
});

// Start server
app.listen(PORT, () => {
    console.log(`🚀 Server is running at http://localhost:${PORT}`);
});


Step 3: create views/partials/header.ejs

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
<nav>
    <a href="/dashboard">Dashboard</a> |
    <a href="/page1">Page 1</a> |
    <a href="/page2">Page 2</a> |
    <a href="/logout">Logout</a>
</nav>
<hr>


Step 4: create views/partials/footer.ejs

<hr>
<footer>
    <p>© 2025 EJS Dashboard</p>
</footer>
</body>
</html>


Step 5: create views/login.ejs

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h2>🔐 Login</h2>

<form method="POST" action="/login">
    <label>Username:</label><br>
    <input type="text" name="username" required><br><br>

    <label>Password:</label><br>
    <input type="password" name="password" required><br><br>

    <button type="submit">Login</button>
</form>

<% if (error) { %>
    <p style="color: red;"><%= error %></p>
<% } %>

</body>
</html>


Step 6: views/dashboard.ejs

<%- include('partials/header') %>
<h1>📊 Welcome, <%= username %>!</h1>
<p>This is your main dashboard.</p>
<%- include('partials/footer') %>


Step 7: views/page1.ejs

<%- include('partials/header') %>
<h2>📁 Page 1</h2>
---------------
---------------
---------------
<p>This is page 1 of your app.</p>
<%- include('partials/footer') %>


Step 8: views/page2.ejs

<%- include('partials/header') %>
<h2>📁 Page 2</h2>
---------------
---------------
---------------
<p>This is page 2 of your app.</p>
<%- include('partials/footer') %>


Step 9: public/css/style.css (Optional styling)

body {
    font-family: Arial, sans-serif;
    margin: 30px;
}

nav a {
    margin-right: 15px;
    text-decoration: none;
    color: darkblue;
}

footer {
    text-align: center;
    font-size: 14px;
    color: gray;
    margin-top: 20px;
}


----------------------------------------------------

(i) To run application  :  node server.js (press enter)
(ii) Here, we can Login using :
     Username: admin
     Password: admin123

Loading

Categories: NodeJs

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.