Pagination, Filtering and Sorting

Large APIs should not return unlimited records. Pagination protects database performance, memory consumption, and response size.

Offset pagination is straightforward and works well for many administrative interfaces. Cursor pagination can be more stable for rapidly changing datasets and large collections.

Filtering and sorting parameters should be validated and constrained. Never directly concatenate arbitrary user input into database queries.

Query Parameters
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const page = Math.max(1, Number(searchParams.get('page') ?? 1));
  const limit = Math.min(100, Math.max(1, Number(searchParams.get('limit') ?? 20)));

  const users = await getUsers({ page, limit });

  return Response.json({ users, page, limit });
}

The handler constrains pagination parameters instead of trusting arbitrary values.

Key Takeaways
  • Always bound pagination parameters.

  • Choose cursor or offset pagination based on workload.

  • Validate sorting and filtering inputs.