How do I implement basic pagination on a MySQL table from a Next.js API route?

clock icon

asked 386 days ago

message icon

1

eye icon

93

Suppose I have hundreds of products in MySQL—how can I let the client request page 1, 2, 3 with a limit and offset in my Next.js handler?

1 Answer

here's how you can do it:

1// pages/api/products.js
2import mysql from 'mysql2/promise';
3
4const pool = mysql.createPool({ /* connection from env */ });
5
6export default async function handler(req, res) {
7 const page = parseInt(req.query.page || '1', 10);
8 const limit = parseInt(req.query.limit || '10', 10);
9 const offset = (page - 1) * limit;
10
11 const [rows] = await pool.execute(
12 'SELECT * FROM products LIMIT ? OFFSET ?',
13 [limit, offset]
14 );
15 res.status(200).json({ page, limit, data: rows });
16}
17
1// pages/api/products.js
2import mysql from 'mysql2/promise';
3
4const pool = mysql.createPool({ /* connection from env */ });
5
6export default async function handler(req, res) {
7 const page = parseInt(req.query.page || '1', 10);
8 const limit = parseInt(req.query.limit || '10', 10);
9 const offset = (page - 1) * limit;
10
11 const [rows] = await pool.execute(
12 'SELECT * FROM products LIMIT ? OFFSET ?',
13 [limit, offset]
14 );
15 res.status(200).json({ page, limit, data: rows });
16}
17
  • Client calls /api/products?page=2&limit=20.
  • LIMIT ? OFFSET ? slices the results.

1

Write your answer here

Top Questions