CoreUI ONE — 250+ PRO components and 25+ admin templates for React, Angular, Vue, Bootstrap and Next.js, plus Data Grid, Scheduler, 4,300+ PRO icons and the Next.js boilerplate. One license. → See what you get

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, 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.
How to set focus on an input field after rendering in React
How to set focus on an input field after rendering in React

Passing props to child components in React function components
Passing props to child components in React function components

How to loop inside React JSX
How to loop inside React JSX

How to validate an email address in JavaScript
How to validate an email address in JavaScript