What if you could change your entire data source by updating just one file?
Why Repository pattern for data access in NextJS? - Purpose & Use Cases
Imagine building a Next.js app where you fetch data directly from the database in many places across your code.
Each time you want to change how data is fetched or stored, you must update many files.
Manually accessing data everywhere makes your code messy and hard to maintain.
If the database changes, you risk breaking many parts of your app.
It's like having many keys for different doors instead of one master key.
The Repository pattern creates a single place to handle all data access.
Your app talks only to this repository, so changes happen in one spot.
This keeps your code clean, easier to test, and safer to update.
const user = await db.query('SELECT * FROM users WHERE id = ?', [id]);const user = await userRepository.getUserById(id);
It enables you to swap databases or change data logic without touching your whole app.
Think of a library where all books are organized in one place, so you don't have to search every shelf yourself.
Manual data access scatters code and causes maintenance headaches.
Repository pattern centralizes data logic for cleaner, safer code.
It makes your app flexible and easier to update or test.
Practice
Repository pattern in a Next.js application?Solution
Step 1: Understand the role of the Repository pattern
The Repository pattern centralizes data access logic, separating it from UI code.Step 2: Identify benefits in Next.js context
This separation makes code cleaner, reusable, and easier to maintain.Final Answer:
To organize data access in one place for cleaner and reusable code -> Option BQuick Check:
Repository pattern = centralized data access [OK]
- Confusing repository with UI state management
- Thinking repository handles routing
- Mixing repository with styling concerns
Solution
Step 1: Check class syntax and async usage
class UserRepository { async getAll() { return fetch('/api/users').then(res => res.json()) } } correctly defines a class with an async method returning parsed JSON from fetch.Step 2: Identify errors in other options
function UserRepository() { return fetch('/api/users') } is a function, not a class. const UserRepository = () => fetch('/api/users').json() incorrectly calls .json() directly on fetch result without awaiting. class UserRepository { getAll() { return fetch('/api/users').json() } } misses async and awaits, causing runtime error.Final Answer:
class UserRepository { async getAll() { return fetch('/api/users').then(res => res.json()) } } -> Option AQuick Check:
Async class method with fetch and json parsing = class UserRepository { async getAll() { return fetch('/api/users').then(res => res.json()) } } [OK]
- Forgetting async keyword on methods
- Calling .json() without awaiting fetch response
- Using function instead of class for repository
console.log(users) output?class UserRepository {
async getAll() {
return [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
}
}
const repo = new UserRepository()
const users = await repo.getAll()
console.log(users)Solution
Step 1: Analyze the getAll method
getAll returns a resolved array of user objects immediately (no fetch or delay).Step 2: Understand await usage
Await unwraps the Promise returned by async getAll, so users is the array itself.Final Answer:
[{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] -> Option AQuick Check:
Await unwraps async return value = array [OK]
- Thinking users is a Promise object
- Forgetting await causes Promise logged
- Assuming undefined without return
class ProductRepository {
getAll() {
const response = fetch('/api/products')
return response.json()
}
}Solution
Step 1: Check fetch usage
fetch returns a Promise, so response is a Promise, not the actual response object.Step 2: Identify missing async/await
To get JSON data, method must be async and await fetch and response.json() calls.Final Answer:
Missing async keyword and await for fetch and json calls -> Option CQuick Check:
Async fetch requires await to get response data [OK]
- Not marking method async
- Not awaiting fetch or json()
- Assuming fetch returns data synchronously
Solution
Step 1: Understand caching in repository context
Caching should be encapsulated inside the repository class to keep data access logic together.Step 2: Evaluate options for caching implementation
class UserRepository { cache = null async getAll() { if (this.cache) return this.cache const res = await fetch('/api/users') this.cache = await res.json() return this.cache } } uses a class property to store cache and returns it if available, avoiding repeated fetch calls.Step 3: Compare other options
Options A and B do not implement caching. const cache = [] async function getAllUsers() { if (cache.length) return cache const res = await fetch('/api/users') cache.push(...await res.json()) return cache } uses an external cache variable, breaking encapsulation.Final Answer:
class UserRepository { cache = null async getAll() { if (this.cache) return this.cache const res = await fetch('/api/users') this.cache = await res.json() return this.cache } } -> Option DQuick Check:
Repository with internal cache property = class UserRepository { cache = null async getAll() { if (this.cache) return this.cache const res = await fetch('/api/users') this.cache = await res.json() return this.cache } } [OK]
- Caching outside repository breaks encapsulation
- Not checking cache before fetching
- Using functions instead of class for caching
Ready to prove it?
Pass the test and this pattern moves unknown
