How to handle sorting in Node.js APIs

Implementing sorting is essential for Node.js APIs that return lists of data, allowing clients to order results by any field. As the creator of CoreUI with over 11 years of Node.js development experience since 2014, I’ve built sortable APIs for countless enterprise applications. The most effective solution is to accept sort field and direction as query parameters and apply them to database queries. This approach is flexible, performant, and follows REST API best practices.

Use query parameters to implement sorting in Node.js APIs.

const express = require('express')
const { User } = require('./models')

const app = express()

app.get('/api/users', async (req, res) => {
  const sortBy = req.query.sortBy || 'createdAt'
  const sortOrder = req.query.order || 'DESC'

  const allowedFields = ['name', 'email', 'createdAt', 'updatedAt']
  const allowedOrders = ['ASC', 'DESC']

  if (!allowedFields.includes(sortBy)) {
    return res.status(400).json({ error: 'Invalid sort field' })
  }

  if (!allowedOrders.includes(sortOrder.toUpperCase())) {
    return res.status(400).json({ error: 'Invalid sort order' })
  }

  const users = await User.findAll({
    order: [[sortBy, sortOrder]]
  })

  res.json(users)
})

The API accepts sortBy and order query parameters with sensible defaults. An allowlist validates the sort field to prevent SQL injection and ensure only valid columns are used. The sort order is validated to accept only ASC or DESC. Sequelize’s order option accepts an array where the first element is the field name and the second is the direction. Multiple sort fields can be supported by passing multiple field-direction pairs.

Best Practice Note

This is the same sorting pattern we use in CoreUI backend APIs for data tables and lists. Always validate sort fields against an allowlist rather than directly using user input in queries. For APIs supporting multiple sort fields, accept a comma-separated list like ?sortBy=name,createdAt&order=ASC,DESC and parse it appropriately.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team