Many developers start their Express apps with everything inside a single app.js or index.js. It works for a "Hello World" project, but as soon as you add Authentication, Database Models, and Business Logic, things get messy. Fast.
After refactoring several production apps, I realized that the secret to a scalable backend isn't just the code you write, but how you organize it.
Here is the "Layered Architecture" I use to keep my sanity:
- The Controller Layer (The Messenger) Controllers should only handle requests and responses. They don't know how the database works; they just pass data to the next layer.
Mistake: Putting SQL queries inside a route handler.
Fix: Keep them thin. If it's more than 10-15 lines, move the logic.
- The Service Layer (The Brain) This is where your business logic lives. If a user registers, the Service Layer handles hashing the password, checking if the email exists, and sending the welcome email.
Why? This makes your logic reusable and much easier to test.
The Model Layer (The Foundation)
Using an ORM like Sequelize helps, but you need a strict structure. Define your associations (One-to-Many, etc.) in a way that doesn't create circular dependencies.The Middleware Layer (The Guard)
Security headers, rate limiting, and JWT validation should be global or route-specific guards. They shouldn't clutter your main logic.
Why This Matters
Building this structure from scratch for every project takes hours of boilerplate workโsetting up folders, configuring Sequelize, mapping JWT flows, and testing Docker containers.
Iโve spent a lot of time perfecting this exact folder structure and flow so that it's both secure and modular. I wanted a system where I could just focus on building features instead of configuring middleware for the 100th time.
If you're looking for a reference on how to implement this layered architecture with a fully functional Auth system, I've shared my implementation on GitHub. It includes:
Clear Controller/Service/Model separation.
Automated Docker setup.
Ready-to-use Auth flows (JWT Rotation).
Check out the architecture here: ๐ https://github.com/Dark353/node-express-mysql-auth-boilerplate
How do you structure your Node.js apps? Do you prefer a flat structure or do you go all-in on clean architecture? Let's discuss in the comments!
Top comments (0)