This pagination approach normalizes and validates query parameters (page and limit) and converts them into safe numeric values. It also calculates the correct offset for database queries, ensuring consistent and reusable pagination logic across all API routes. By centralizing it into a utility, it eliminates duplication and keeps pagination behavior uniform throughout the application.
export const getPagination = (query: any) => {
const page = Math.max(1, parseInt(query.page ?? "1", 10) || 1);
const limit = Math.min(50, Math.max(1, parseInt(query.limit ?? "10", 10) || 10));
return {
page,
limit,
offset: (page - 1) * limit,
};
};