0
0
Firebasecloud~5 mins

Limit and pagination in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you have many items in a database, showing them all at once can be slow and confusing. Limit and pagination help you see a small number of items at a time, making it faster and easier to use.
When you want to show only 10 messages at a time in a chat app.
When you have a list of products and want to show 20 per page in an online store.
When you want to load more posts as the user scrolls down a social media feed.
When you want to reduce data usage by loading small chunks of data instead of everything.
When you want to improve app speed by loading data step-by-step.
Commands
This command fetches the first 5 items from the 'products' collection to limit the data shown at once.
Terminal
firebase firestore:query --collection=products --limit=5
Expected OutputExpected
[ {"id": "prod1", "name": "Shoes", "price": 50}, {"id": "prod2", "name": "Hat", "price": 20}, {"id": "prod3", "name": "Jacket", "price": 100}, {"id": "prod4", "name": "Socks", "price": 5}, {"id": "prod5", "name": "T-shirt", "price": 15} ]
--collection - Specifies which collection to query
--limit - Limits the number of results returned
This command fetches the next 5 items after the last item with id 'prod5' to continue pagination.
Terminal
firebase firestore:query --collection=products --limit=5 --startAfter=prod5
Expected OutputExpected
[ {"id": "prod6", "name": "Gloves", "price": 25}, {"id": "prod7", "name": "Scarf", "price": 30}, {"id": "prod8", "name": "Belt", "price": 10}, {"id": "prod9", "name": "Sunglasses", "price": 60}, {"id": "prod10", "name": "Watch", "price": 150} ]
--startAfter - Starts the query after the specified document id for pagination
Key Concept

If you remember nothing else from this pattern, remember: use limit to control how many items you get and startAfter to get the next set of items for smooth pagination.

Common Mistakes
Not using startAfter or startAt for pagination and always fetching from the beginning.
This causes repeated data and slow loading because you fetch the same items again.
Use startAfter with the last item from the previous query to fetch the next page.
Setting limit too high and loading too many items at once.
This slows down the app and uses more data than needed.
Choose a reasonable limit like 5 or 10 to keep loading fast and smooth.
Summary
Use the limit flag to get a small number of items from a collection.
Use startAfter with the last item id to get the next page of items.
This approach helps load data step-by-step, improving speed and user experience.