What if changing your database didn't mean rewriting half your app?
Why Repository pattern for data access in Express? - Purpose & Use Cases
Imagine building an app where you write raw database queries everywhere in your Express routes. Every time you want to change how data is fetched or saved, you must hunt through all your files to update those queries.
Scattering database code all over makes your app hard to maintain and test. If the database changes, you risk breaking many parts. It's slow to add features or fix bugs because you repeat similar code everywhere.
The Repository pattern creates a single place to handle all data access. Your routes just ask the repository for data, so you can change database details inside the repository without touching the rest of your app.
app.get('/users', (req, res) => { db.query('SELECT * FROM users', (err, results) => { res.send(results); }); });
class UserRepository { getAll() { return db.query('SELECT * FROM users'); } } const userRepository = new UserRepository(); app.get('/users', async (req, res) => { const users = await userRepository.getAll(); res.send(users); });
This pattern lets you swap databases, add caching, or change queries easily without rewriting your whole app.
When your app grows and you switch from a simple JSON file to a real database, the Repository pattern lets you make that change smoothly without breaking your routes.
Manual data access scattered in routes is hard to maintain.
Repository pattern centralizes data logic for easier updates.
It improves app flexibility, testing, and scalability.