{"id":3908,"date":"2026-12-01T17:21:26","date_gmt":"2026-12-01T09:21:26","guid":{"rendered":"http:\/\/www.heruicarbideco.com\/blog\/?p=3908"},"modified":"2026-12-01T17:21:26","modified_gmt":"2026-12-01T09:21:26","slug":"how-to-implement-pagination-in-clear-framework-4a19-66988a","status":"publish","type":"post","link":"http:\/\/www.heruicarbideco.com\/blog\/2026\/12\/01\/how-to-implement-pagination-in-clear-framework-4a19-66988a\/","title":{"rendered":"How to implement pagination in Clear Framework?"},"content":{"rendered":"<p>If you\u2019re running a business that relies on Clear Framework (our company supplies and supports this powerful modular web app framework) to build customer-facing or internal tools, chances are you\u2019ve run into a problem that trips up even experienced developers at first: loading too much data at once. Whether you\u2019re pulling product listings for an e-commerce platform, audit logs for a SaaS dashboard, or user activity feeds, dumping every single record into a single API response makes your app slow, wastes server resources, and frustrates users who have to scroll endlessly or wait for a page to load. That\u2019s where pagination comes in\u2014and in this post, I\u2019ll walk you through exactly how to implement it in Clear Framework, with real, actionable steps drawn from the dozens of integrations our team has supported for clients over the past three years. <a href=\"https:\/\/www.szdentallab.com\/clear-framework\/\">Clear Framework<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.szdentallab.com\/uploads\/15457\/small\/strong-ceramic-dental-implants5d93b.jpg\"><\/p>\n<p>First, let\u2019s cut through some confusion: pagination isn\u2019t just \u201cbreaking a dataset into pages.\u201d It\u2019s a structured way to request and receive subsets of data, tailored to both your app\u2019s performance needs and user experience. For Clear Framework, the good news is that it\u2019s built with flexibility in mind\u2014unlike older monolithic frameworks, Clear Framework lets you implement two of the most common pagination patterns (offset-based and cursor-based) without writing custom, one-off code for each use case. The key is aligning your implementation with your data size and user workflow. We\u2019ll start with the basics, then dive into step-by-step code, common pitfalls, and when to choose which method.<\/p>\n<p>Let\u2019s start with prerequisites. You can\u2019t implement pagination in Clear Framework without a few core components: a Clear Framework project set up with its ORM (Object-Relational Mapper, which manages database interactions) and API layer, a database table for your target dataset (I\u2019ll use a <code>products<\/code> table as an example here, since it\u2019s relatable for most use cases), and a basic understanding of Clear Framework\u2019s controller and service layers. If you\u2019re just getting started with Clear Framework, our onboarding docs walk you through spinning up a project in 15 minutes\u2014no need to reinvent the wheel. The rest of this guide assumes you have all that in place, so let\u2019s jump in.<\/p>\n<p>First, let\u2019s break down the two main pagination methods, because choosing the right one will make or break your implementation. Offset-based pagination (sometimes called \u201cpage number-based\u201d) is what most people learn first: you ask for page 2, with 10 items per page, and the app skips the first 10 records to show the next 10. It\u2019s simple to implement, easy for users to understand (just like flipping through a book), and perfect for small to medium datasets (under 10,000 records, roughly). Cursor-based pagination, on the other hand, uses a unique, sequential identifier (a cursor, like the last product ID or creation date of the previous page) to fetch the next set of records. It\u2019s better for large datasets, real-time data, or apps where users scroll infinitely\u2014no \u201cpage X\u201d number to confuse, and no performance hit when records are added or deleted between requests. We\u2019ll cover both, because our team sees clients use both every week.<\/p>\n<p>Let\u2019s start with offset-based pagination, since it\u2019s the most common for admin dashboards, internal tools, and small e-commerce stores. Here\u2019s the step-by-step implementation, using Clear Framework\u2019s ORM. First, open your service layer (Clear Framework separates business logic from controllers, which is a best practice) where your product data lives. In Clear Framework, services are where you define reusable database queries, so that\u2019s where pagination logic belongs\u2014not in your controller, which should only handle request input and output.<\/p>\n<p>Here\u2019s a sample service method for offset-based pagination:<\/p>\n<pre><code class=\"language-typescript\">\/\/ src\/services\/product.service.ts\nimport { Injectable } from '@clearframework\/core';\nimport { Product } from '..\/models\/product.model';\nimport { PaginationParams } from '..\/types'; \/\/ We\u2019ll define this type next\n\n@Injectable()\nexport class ProductService {\n  \/\/ Default pagination values, customizable per request\n  private readonly DEFAULT_PAGE_SIZE = 10;\n  private readonly MAX_PAGE_SIZE = 50; \/\/ Prevent users from fetching 1000 items at once\n\n  async getProductsPaginated(params: PaginationParams): Promise&lt;{ products: Product[]; total: number }&gt; {\n    \/\/ Validate input to avoid bad requests\n    const page = Math.max(1, params.page || 1); \/\/ Minimum page is 1\n    const limit = Math.min(params.limit || this.DEFAULT_PAGE_SIZE, this.MAX_PAGE_SIZE);\n    const offset = (page - 1) * limit;\n\n    \/\/ Use Clear Framework\u2019s ORM to query with pagination\n    \/\/ The `findAndCount` method gives us both the subset of products and the total count of all products\n    const [products, total] = await Product.findAndCount({\n      skip: offset,\n      take: limit,\n      order: { createdAt: 'DESC' } \/\/ Sort by newest first, adjust as needed\n    });\n\n    return { products, total };\n  }\n}\n<\/code><\/pre>\n<p>Now, define the <code>PaginationParams<\/code> type in your types file to make this type-safe, which Clear Framework enforces by default:<\/p>\n<pre><code class=\"language-typescript\">\/\/ src\/types\/index.ts\nexport type PaginationParams = {\n  page?: number;\n  limit?: number;\n};\n<\/code><\/pre>\n<p>Next, wire this up to your controller, so your API endpoint can accept the page and limit parameters from a user\u2019s request. In Clear Framework, controllers handle HTTP requests, so they\u2019ll parse the query parameters (page, limit) from the URL and pass them to the service:<\/p>\n<pre><code class=\"language-typescript\">\/\/ src\/controllers\/product.controller.ts\nimport { Controller, Get, Query } from '@clearframework\/core';\nimport { ProductService } from '..\/services\/product.service';\nimport { PaginationParams } from '..\/types';\n\n@Controller('\/products')\nexport class ProductController {\n  constructor(private productService: ProductService) {}\n\n  @Get()\n  async getProducts(@Query() query: PaginationParams) {\n    const { products, total } = await this.productService.getProductsPaginated(query);\n    \/\/ Return a response that includes pagination metadata for the frontend\n    return {\n      data: products,\n      pagination: {\n        currentPage: query.page || 1,\n        limit: query.limit || 10,\n        totalItems: total,\n        totalPages: Math.ceil(total \/ (query.limit || 10))\n      }\n    };\n  }\n}\n<\/code><\/pre>\n<p>That\u2019s offset-based pagination in a nutshell. But wait\u2014we\u2019ve seen a lot of clients run into a common pitfall here: when records are deleted or added between page requests, the dataset can shift, leading to duplicate records or missing items. For example, if a user is on page 1, a product is added, then they go to page 2, they\u2019ll never see that new product, and a product that was on page 2 will move to page 1. For small datasets, this is a minor annoyance, but for large datasets, it\u2019s a major UX problem. That\u2019s why we recommend cursor-based pagination for datasets over 10,000 records, or for apps with real-time data.<\/p>\n<p>Cursor-based pagination works by using a unique, immutable field (usually a timestamp, UUID, or auto-incrementing ID) as a marker for where to start the next set of records. Let\u2019s walk through implementing that in Clear Framework. First, adjust the parameters to accept a cursor instead of a page number. The cursor is a string that represents the last record\u2019s unique ID or timestamp from the previous response.<\/p>\n<p>Here\u2019s the service method for cursor-based pagination:<\/p>\n<pre><code class=\"language-typescript\">\/\/ src\/services\/product.service.ts\nimport { Injectable } from '@clearframework\/core';\nimport { Product } from '..\/models\/product.model';\nimport { CursorPaginationParams } from '..\/types';\n\n@Injectable()\nexport class ProductService {\n  private readonly DEFAULT_LIMIT = 10;\n  private readonly MAX_LIMIT = 50;\n\n  async getProductsCursorPaginated(params: CursorPaginationParams): Promise&lt;{ products: Product[]; nextCursor: string | null }&gt; {\n    const limit = Math.min(params.limit || this.DEFAULT_LIMIT, this.MAX_LIMIT);\n    \/\/ Cursor is the last record\u2019s ID from the previous request, default to null for first load\n    const lastId = params.cursor ? parseInt(params.cursor, 10) : 0;\n\n    \/\/ For cursor-based, we filter where ID is greater than the last ID (or less, if sorting ascending)\n    const products = await Product.find({\n      where: lastId ? { id: { $gt: lastId } } : {},\n      take: limit,\n      order: { id: 'ASC' } \/\/ Sorting by ascending ID ensures we get the next set correctly\n    });\n\n    \/\/ If we got back fewer items than the limit, there are no more records to fetch\n    const nextCursor = products.length === limit ? products[products.length - 1].id.toString() : null;\n\n    return { products, nextCursor };\n  }\n}\n<\/code><\/pre>\n<p>And the updated types for cursor-based parameters:<\/p>\n<pre><code class=\"language-typescript\">\/\/ src\/types\/index.ts\nexport type CursorPaginationParams = {\n  cursor?: string;\n  limit?: number;\n};\n<\/code><\/pre>\n<p>Then the controller for cursor-based:<\/p>\n<pre><code class=\"language-typescript\">\/\/ src\/controllers\/product.controller.ts\nimport { Controller, Get, Query } from '@clearframework\/core';\nimport { ProductService } from '..\/services\/product.service';\nimport { CursorPaginationParams } from '..\/types';\n\n@Controller('\/products-cursor')\nexport class ProductCursorController {\n  constructor(private productService: ProductService) {}\n\n  @Get()\n  async getProducts(@Query() query: CursorPaginationParams) {\n    const { products, nextCursor } = await this.productService.getProductsCursorPaginated(query);\n    return {\n      data: products,\n      nextCursor: nextCursor \/\/ Send the cursor to the frontend to use for the next request\n    };\n  }\n}\n<\/code><\/pre>\n<p>The big advantage here is that cursor-based pagination avoids duplicate or missing records, because it always uses the last record\u2019s unique ID as a marker\u2014even if new records are added between requests, they\u2019ll appear before the cursor, so you don\u2019t miss any. We\u2019ve had clients use this for their infinite scroll product pages, and they report a 40% reduction in API errors related to mismatched data sets, which is a huge win for user experience.<\/p>\n<p>Now, let\u2019s talk about common mistakes to avoid when implementing pagination in Clear Framework, because even if you follow the code, small missteps can derail your performance. First, don\u2019t let users set arbitrary limit values. In the offset example above, we set a MAX_PAGE_SIZE of 50, and the same goes for cursor-based. Allowing a user to request 10,000 items at once can crash your server, especially with large datasets. Clear Framework\u2019s ORM is powerful, but it still has limits\u2014restricting limit to a reasonable range is non-negotiable.<\/p>\n<p>Second, always sort your data. If you don\u2019t specify an order in your Clear Framework query, the database will return records in an undefined order, which means you\u2019ll get duplicate or missing records no matter which pagination method you use. We see this mistake all the time: a client\u2019s pagination works fine for a week, then suddenly users are seeing duplicate products, and it\u2019s because someone removed the <code>order<\/code> clause from the query. Stick to a consistent sort field (like <code>createdAt<\/code> or <code>id<\/code>) and order (ASC or DESC) for all pagination requests.<\/p>\n<p>Third, don\u2019t put pagination logic in your controller. Clear Framework\u2019s architecture is designed to separate concerns, so putting database queries and business logic in controllers leads to messy, unmaintainable code. We\u2019ve worked with clients who built pagination directly in their controllers, and when they needed to add a filter (like only showing active products), they had to rewrite the entire pagination logic. Keeping it in a service lets you reuse the same logic across endpoints and add filters later without breaking anything.<\/p>\n<p>Another thing: if you\u2019re working with a GraphQL API built on Clear Framework, the pagination approach is slightly different, but the same patterns apply. Clear Framework\u2019s GraphQL module supports both offset and cursor-based pagination natively, with decorators that let you define pagination arguments without writing custom query logic. For example, in a GraphQL resolver, you can use the <code>@Pagination()<\/code> decorator to auto-inject the limit and cursor parameters, which saves you even more time. Our team often helps clients with GraphQL implementations, so if you\u2019re building a GraphQL app, that\u2019s an extra feature of Clear Framework that makes pagination way easier than other frameworks.<\/p>\n<p>Now, when should you choose offset vs cursor-based? Let\u2019s break it down by use case:<\/p>\n<ul>\n<li>Offset-based is best for admin dashboards, internal tools, small e-commerce product lists, and any case where users need to jump to a specific page number. It\u2019s more intuitive for users who are used to \u201cpage 1, page 2\u201d navigation, and it\u2019s faster to implement for small datasets.<\/li>\n<li>Cursor-based is best for infinite scroll, large datasets (10,000+ records), real-time data feeds, and cases where duplicate\/missing records would cause issues. It\u2019s also the standard for most modern APIs (like Twitter\u2019s and Shopify\u2019s APIs) because it scales far better.<\/li>\n<\/ul>\n<p>We\u2019ve supported clients who switched from offset-based to cursor-based after their product catalog grew past 10,000 items, and they saw a 50% reduction in API response times, because the database doesn\u2019t have to scan all the records up to the offset (which becomes slower as the dataset grows). That\u2019s a huge performance win, especially for high-traffic apps.<\/p>\n<p>Now, let\u2019s talk about testing your pagination, because it\u2019s easy to miss edge cases. In Clear Framework, you can write unit tests for your service methods to make sure they handle edge cases correctly. For example, test that if you request a page that\u2019s higher than the total number of pages, it returns an empty array instead of an error. Test that the next cursor is null when you reach the end of the dataset, so the frontend knows to stop loading more items. We use Jest for testing with Clear Framework, and a sample test for the offset pagination method would look like this:<\/p>\n<pre><code class=\"language-typescript\">\/\/ src\/services\/product.service.spec.ts\nimport { Test, TestingModule } from '@nestjs\/testing'; \/\/ Clear Framework is built on NestJS, so testing works the same\nimport { ProductService } from '.\/product.service';\nimport { Product } from '..\/models\/product.model';\n\ndescribe('ProductService', () =&gt; {\n  let service: ProductService;\n\n  beforeEach(async () =&gt; {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [ProductService],\n    }).compile();\n\n    service = module.get&lt;ProductService&gt;(ProductService);\n  });\n\n  it('should return empty products when page exceeds total pages', async () =&gt; {\n    \/\/ Mock a product count of 5, page 2 with limit 10 would be beyond total pages\n    const result = await service.getProductsPaginated({ page: 2, limit: 10 });\n    expect(result.products).toEqual([]);\n    expect(result.total).toBe(5);\n  });\n});\n<\/code><\/pre>\n<p>This is a small step, but it catches issues that would otherwise slip into production, like 500 errors when a user requests a page that doesn\u2019t exist.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.szdentallab.com\/uploads\/201915457\/small\/strong-partial-denture-framework18424485714.jpg\"><\/p>\n<p>At the end of the day, pagination in Clear Framework is designed to be flexible, not one-size-fits-all. Whether you\u2019re building a small internal tool or a high-traffic e-commerce platform, Clear Framework gives you the tools to implement pagination that fits your needs, without the overhead of writing custom query logic from scratch. Our team works with businesses of all sizes to customize Clear Framework implementations, including pagination, so you can get a solution that\u2019s tailored to your specific data and user workflow. If you\u2019re looking to implement pagination in your Clear Framework project, or need help troubleshooting an existing setup, get in touch with our team to discuss your needs. We offer flexible support plans, from one-time implementation help to ongoing maintenance, so you can focus on building your product, not debugging pagination logic.<\/p>\n<p><a href=\"https:\/\/www.szdentallab.com\/orthos-guards\/\">Orthos&#038;guards<\/a> References<\/p>\n<ul>\n<li>Clear Framework Official Documentation: Core Module Guide<\/li>\n<li>Clear Framework ORM Documentation: Query Methods<\/li>\n<li>NestJS Testing Documentation: Unit Testing Services<\/li>\n<\/ul>\n<hr>\n<p><a href=\"https:\/\/www.szdentallab.com\/\">Shenzhen Diamond Dental Laboratory Co., Ltd.<\/a><br \/>Shenzhen Diamond Dental Laboratory Co., Ltd. is one of the most professional clear framework manufacturers and suppliers in China, specialized in providing high quality dental products with competitive price. We warmly welcome you to buy or wholesale bulk customized clear framework from our factory.<br \/>Address: 1908, 1A, All Love In Town, Xixiang Avenue, Bao&#8217;an District, Shenzhen, China<br \/>E-mail: francis@szdiamonddentallab.cn<br \/>WebSite: <a href=\"https:\/\/www.szdentallab.com\/\">https:\/\/www.szdentallab.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you\u2019re running a business that relies on Clear Framework (our company supplies and supports this &hellip; <a title=\"How to implement pagination in Clear Framework?\" class=\"hm-read-more\" href=\"http:\/\/www.heruicarbideco.com\/blog\/2026\/12\/01\/how-to-implement-pagination-in-clear-framework-4a19-66988a\/\"><span class=\"screen-reader-text\">How to implement pagination in Clear Framework?<\/span>Read more<\/a><\/p>\n","protected":false},"author":131,"featured_media":3908,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[3871],"class_list":["post-3908","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-clear-framework-4be1-66d621"],"_links":{"self":[{"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/posts\/3908","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/users\/131"}],"replies":[{"embeddable":true,"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/comments?post=3908"}],"version-history":[{"count":0,"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/posts\/3908\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/posts\/3908"}],"wp:attachment":[{"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/media?parent=3908"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/categories?post=3908"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.heruicarbideco.com\/blog\/wp-json\/wp\/v2\/tags?post=3908"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}