Project 5: An Employee Management System

Node.js and Express: Build a Back End API from Scratch · Ten Portfolio Projects · 9 min read · Updated

Same URL, different rows

  1. HR and admins receive the full list.
  2. A manager receives only the people in their department.
  3. An employee receives only their own record. The server decides, not the front end.
  4. Attendance allows one check-in and one check-out per employee per day.

Company software is where role-based access control becomes interesting, because the rules are not only about actions but about *which rows* a person may see. An HR officer sees everyone. A manager sees only their department. An employee sees only themselves. This project builds an employee system with departments and attendance, and its main lesson is the idea of scoping: the same URL returns different data to different users.

What you will build

  • Admins and HR create departments and employees.
  • GET /api/employees returns all employees to HR and admins, the department to a manager, and only themselves to an employee.
  • Soft delete: removing an employee keeps their history.
  • Employees check in and check out once a day.
  • Admins, HR and managers read attendance.

Design decisions before any code

There are four roles: admin, hr, manager and employee. Every employee belongs to a department, and managers belong to the department they manage. A route that lists data must filter by what the caller is allowed to see, and the filter belongs on the server, never in the front end. A front end that hides rows is decoration. The API must refuse to send them.

Deleting an employee changes a field, active: false, instead of removing the record. Attendance history, payroll history and audit trails refer to the person, so the record must stay. Deactivated employees can no longer check in.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express jsonwebtoken.
  3. Copy p-kit.js, p05-employees.js and p05.test.js into the folder. The shared p-kit.js is in Project 1.
  4. Install the test tools with npm install -D supertest, then run node --test p05.test.js.

Read the list route first, because it contains the scoping rule. Then read the two attendance routes.

// Project 5: employees, departments, attendance and permissions (admin, hr, manager, employee).
import express from 'express';
import { AppError, requireAuth, requireRole, errorHandler, notFoundHandler } from './p-kit.js';

const today = (now) => now().toISOString().slice(0, 10);

export function createApp({ now = () => new Date() } = {}) {
  const app = express();
  app.use(express.json());
  const auth = requireAuth();
  const departments = new Map();
  const employees = new Map();
  const attendance = [];       // { employeeId, date, checkIn, checkOut }

  app.post('/api/departments', auth, requireRole('admin', 'hr'), (req, res) => {
    const name = String(req.body?.name ?? '').trim();
    if (!name) throw new AppError('name is required', 422);
    if ([...departments.values()].some((d) => d.name.toLowerCase() === name.toLowerCase())) throw new AppError('Department exists', 409);
    const department = { id: departments.size + 1, name };
    departments.set(department.id, department);
    res.status(201).json(department);
  });

  app.post('/api/employees', auth, requireRole('admin', 'hr'), (req, res) => {
    const { name, departmentId, userId } = req.body ?? {};
    if (!name || !departments.has(departmentId)) throw new AppError('name and a real departmentId are required', 422);
    const employee = { id: employees.size + 1, name, departmentId, userId: userId ?? null, active: true };
    employees.set(employee.id, employee);
    res.status(201).json(employee);
  });

  // Who may see which employees: hr and admin see all, a manager sees their own department, an employee only themselves.
  app.get('/api/employees', auth, (req, res) => {
    const all = [...employees.values()];
    if (['admin', 'hr'].includes(req.user.role)) return res.json(all);
    const me = all.find((e) => e.userId === req.user.id);
    if (req.user.role === 'manager' && me) return res.json(all.filter((e) => e.departmentId === me.departmentId));
    res.json(me ? [me] : []);
  });

  // Soft delete: keep the history, just stop the person from working.
  app.delete('/api/employees/:id', auth, requireRole('admin', 'hr'), (req, res) => {
    const employee = employees.get(Number(req.params.id));
    if (!employee) throw new AppError('Employee not found', 404);
    employee.active = false;
    res.status(204).end();
  });

  const myEmployee = (req) => {
    const employee = [...employees.values()].find((e) => e.userId === req.user.id && e.active);
    if (!employee) throw new AppError('You are not an active employee', 403);
    return employee;
  };

  app.post('/api/attendance/check-in', auth, (req, res) => {
    const employee = myEmployee(req);
    if (attendance.some((a) => a.employeeId === employee.id && a.date === today(now))) throw new AppError('Already checked in today', 409);
    const record = { employeeId: employee.id, date: today(now), checkIn: now().toISOString(), checkOut: null };
    attendance.push(record);
    res.status(201).json(record);
  });

  app.post('/api/attendance/check-out', auth, (req, res) => {
    const employee = myEmployee(req);
    const record = attendance.find((a) => a.employeeId === employee.id && a.date === today(now));
    if (!record) throw new AppError('Check in first', 409);
    if (record.checkOut) throw new AppError('Already checked out', 409);
    record.checkOut = now().toISOString();
    record.hours = Math.round(((new Date(record.checkOut) - new Date(record.checkIn)) / 3_600_000) * 100) / 100;
    res.json(record);
  });

  app.get('/api/attendance', auth, requireRole('admin', 'hr', 'manager'), (req, res) => {
    const { date } = req.query;
    res.json(attendance.filter((a) => !date || a.date === date));
  });

  app.use(notFoundHandler, errorHandler);
  return app;
}

The clock is a parameter again, so the test can pretend that it is a different day without waiting.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './p05-employees.js';
import { signToken } from './p-kit.js';

const as = (id, role) => ({ Authorization: `Bearer ${signToken({ id, role, name: `u${id}` })}` });

test('project 5: departments, visibility and attendance', async () => {
  let clock = new Date('2026-11-10T09:00:00Z');
  const app = createApp({ now: () => clock });
  const hr = as(1, 'hr');

  assert.equal((await request(app).post('/api/departments').set(as(5, 'employee')).send({ name: 'Eng' })).status, 403);
  await request(app).post('/api/departments').set(hr).send({ name: 'Engineering' });
  await request(app).post('/api/departments').set(hr).send({ name: 'Sales' });
  assert.equal((await request(app).post('/api/departments').set(hr).send({ name: 'engineering' })).status, 409);

  await request(app).post('/api/employees').set(hr).send({ name: 'Asha', departmentId: 1, userId: 10 });
  await request(app).post('/api/employees').set(hr).send({ name: 'Ravi', departmentId: 1, userId: 11 });
  await request(app).post('/api/employees').set(hr).send({ name: 'Meera', departmentId: 2, userId: 12 });
  assert.equal((await request(app).post('/api/employees').set(hr).send({ name: 'X', departmentId: 99 })).status, 422);

  assert.equal((await request(app).get('/api/employees').set(hr)).body.length, 3);
  assert.deepEqual((await request(app).get('/api/employees').set(as(10, 'manager'))).body.map((e) => e.name), ['Asha', 'Ravi']);
  assert.deepEqual((await request(app).get('/api/employees').set(as(12, 'employee'))).body.map((e) => e.name), ['Meera']);

  const asha = as(10, 'employee');
  assert.equal((await request(app).post('/api/attendance/check-out').set(asha)).status, 409);
  assert.equal((await request(app).post('/api/attendance/check-in').set(asha)).status, 201);
  assert.equal((await request(app).post('/api/attendance/check-in').set(asha)).status, 409);
  clock = new Date('2026-11-10T17:30:00Z');
  const out = await request(app).post('/api/attendance/check-out').set(asha);
  assert.equal(out.body.hours, 8.5);

  assert.equal((await request(app).get('/api/attendance?date=2026-11-10').set(hr)).body.length, 1);
  assert.equal((await request(app).get('/api/attendance').set(asha)).status, 403);

  await request(app).delete('/api/employees/1').set(hr);
  clock = new Date('2026-11-11T09:00:00Z');
  assert.equal((await request(app).post('/api/attendance/check-in').set(asha)).status, 403);      // no longer active
});

Rules worth understanding

Scoping by role. The list route starts with every employee and narrows it: no change for admin and hr, only the manager's own department for a manager, and only the person's own record for an employee. Test each role on the same URL and compare the results.

One check-in per day. The attendance record has the employee id and the date. A second check-in on the same date answers 409. Check-out is allowed only after a check-in, and only once. The date comes from the server clock, in one known time zone, never from the client, because a client could claim any day.

Soft delete. DELETE sets active to false and keeps the record. Listing, check-in and reports must then agree on how they treat inactive people, and a test should protect that decision.

Unique department names. Names are compared in lower case, so Sales and sales are the same department and the second one answers 409.

Security and honesty notes

Personal data about employees is sensitive, and in many countries the law controls how it is stored and who may see it. Collect only what you need, protect it with the role checks shown here, log who reads sensitive records, and ask for professional advice before you use anything like this with real people.

Time zones are a classic source of bugs. Decide on the zone of the company, and calculate the date in it, rather than using the server's local time by accident.

Extend it

Your task

  1. Add leave requests with a status of pending, approved or rejected, approved by the manager.
  2. Add a monthly attendance report with an aggregation pipeline.
  3. Add an audit log that records who viewed or changed employee records.

How to check it worked

  • The same URL returns different rows for each of the four roles.
  • A second check-in on one day returns 409.
  • A deactivated employee cannot check in.

On your resume. "Built an HR API with four roles, department-scoped data access, attendance tracking and soft delete, with tests for each permission" is a good description. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.

Frequently asked questions

What is soft delete?

Marking a record inactive instead of removing it, so history and reports that refer to it keep working.

Why is hiding rows in the front end not enough?

Anyone can call the API without the front end. Only the server can refuse to send data.

Where should the attendance date come from?

From the server clock in a fixed time zone. A client could send any date.

Practise with interview questions