node-backend-boilerplate-template
v1.0.1
Published
<!-- [](https://www.npmjs.com/package/your-backend-boilerplate) [](https://opensource.org/licenses/MIT) -->
Downloads
2
Maintainers
Readme
🚀 Your Backend Boilerplate Name
A quick and easy way to bootstrap new backend projects with a pre-configured structure for controllers, routes, and services. Get started with your API development in minutes!
✨ Features
- Standardized Structure: Consistent folder organization for
controllers,ServiceRespositryroutes,services, etc. - Ready-to-use: Basic
app.ts(orindex.js) setup for quick starts. - Scalable: Designed to be easily expandable for growing projects.
- Fast Setup: Generate a new project with a single command.
📦 Installation & Usage
To generate a new backend project using this boilerplate, simply run the following command in your terminal:
npx-create-node-backend-boilerplate-template <your-project-name>Psudo code:
- Controller
export class UserController {
constructor(private userService: UserService) {}
// Create a new user
public registerUser = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { user, token } = await this.userService.registerUser(req.body);
res.cookie("token", token, cookieOptions);
sendResponse(
req,
res,
httpStatusCodes.created,
userResponseMessage.created,
user,
{ token }
);
} catch (error) {
next(error);
}
};
}- Service
export class UserService extends BaseService<IUser> {
private readonly userRepository: UserRepository;
constructor(userRepository: UserRepository) {
super(userRepository);
this.userRepository = userRepository;
}
// Create a new user
public async registerUser(
userData: Partial<IUser>
): Promise<{ user: IUser; token: string }> {
const data = { ...userData };
const existingUser = await this.userRepository.findOne({
phoneNo: userData.phoneNo,
});
if (existingUser) {
throw new CustomError(
httpStatusCodes.conflict,
userResponseMessage.alreadyRegister
);
}
if(userData.rating){
delete userData.rating
}
userData.password = await this.generateHashedPassword(userData.password!);
await this.createDocument(userData); //as IUser & Document
const { user, token } = await this.loginUser(data);
return { user, token };
}
}- Respository
import { BaseRepository } from "./BaseRepository";
import { IUser, UserModel } from "../models/UserModel";
export class UserRepository extends BaseRepository<IUser> {
constructor() {
super(UserModel); // 🔥 Pass the Mongoose Model to BaseRepository
}
}
- Routes
class UserRoutes {
router: Router;
constructor(private userController: UserController) {
this.router = Router();
this.initializeRoutes();
}
private initializeRoutes() {
this.router.post(
"/register",
ValidationMiddleware(UserDTO.pick({ phoneNo: true, password: true, name: true })),
this.userController.registerUser
);
}
const userRepository = new UserRepository();
const userService = new UserService(userRepository);
const userController = new UserController(userService);
export const userRoutes = new UserRoutes(userController).router;
- App
import express from 'express'
import cors from 'cors'
import helmet from 'helmet'
import dotenv from 'dotenv'
import cookieParser from 'cookie-parser'
import Database from './config/Database'
import { globalErrorHandler } from './middlewares/globalErrorHandler'
import path from 'path'
import { userRoutes } from './routes/UserRoutes'
dotenv.config()
class App {
public app: express.Application
constructor () {
// 1. Initialize core Express application first
this.app = express()
// 2. Configure middleware (security, parsers, etc.)
this.config()
// 3. Establish database connection
this.connectDatabase()
// 4. Initialize all route instances (after database connection)
// this.testRoutes = new testRoutes()
// 5. Register routes (after middleware and route initialization)
this.routes()
// 6. Add error handling (LAST - after all other middleware/routes)
this.handleErrors()
}
private config (): void {
this.app.use(cookieParser())
this.app.use(cors())
this.app.use(helmet())
this.app.use(express.json())
// ✅ Set EJS as the templating engine
this.app.set('view engine', 'ejs')
// this.app.set('views', path.join(__dirname, 'views'))
this.app.set('views', path.join(__dirname, '../views'))
// ✅ Serve static files correctly
this.app.use('/public', express.static('public'))
}
private connectDatabase (): void {
console.log('Connecting to database...')
Database.connect()
}
private routes (): void {
this.app.use('/api/v1/users', userRoutes)
}
private handleErrors (): void {
this.app.use(globalErrorHandler) // Global error handler should be the last middleware
}
}
export default new App().app
