Backend Architecture
Controllers & Services
The server employs a strict separation of concerns between HTTP transport controllers and database service layers.
Architectural Responsibilities
Controllers (HTTP Layer)
Extract and sanitize parameters from req.body and req.cookies, delegate to services, set HTTP-only response cookies, and return typed JSON contracts with appropriate status codes.
Services (Domain Layer)
Contain business rules, execute Mongoose queries, handle password hashing via bcryptjs, sign JWT credentials, and ensure sensitive fields remain excluded.
Auth Controller Example (`server/src/controllers/auth.controller.ts`)
Controllers are exported as discrete named functions for clear readability and strict type checking:
auth.controller.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { Request, Response } from 'express';
import { signupUser, authenticateUser } from '../services/auth.service.js';
export async function signup(req: Request, res: Response): Promise {
const { name, email, password } = req.body;
const { user, token } = await signupUser({ name, email, password });
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 7 * 24 * 60 * 60 * 1000
});
res.status(201).json({
user,
token
});
}
export async function login(req: Request, res: Response): Promise {
const { email, password } = req.body;
const { user, token } = await authenticateUser({ email, password });
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 7 * 24 * 60 * 60 * 1000
});
res.status(200).json({
user,
token
});
}
export async function logout(req: Request, res: Response): Promise {
res.clearCookie('token');
res.status(200).json({ message: 'Logged out successfully' });
} Auth Service Example (`server/src/services/auth.service.ts`)
The service handles credential verification, password hashing, and token generation:
auth.service.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { User, IUser } from '../models/user.model.js';
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-key';
const SALT_ROUNDS = 12;
export async function signupUser(input: Pick) {
const existing = await User.findOne({ email: input.email });
if (existing) {
const error: any = new Error('Email already registered');
error.statusCode = 409;
throw error;
}
const hashedPassword = await bcrypt.hash(input.password, SALT_ROUNDS);
const user = await User.create({
name: input.name,
email: input.email,
password: hashedPassword,
role: 'member'
});
const token = jwt.sign(
{ id: user._id, role: user.role },
JWT_SECRET,
{ expiresIn: '7d' }
);
return {
user: {
id: user._id,
name: user.name,
email: user.email,
role: user.role
},
token
};
}