How to parse URL parameters in Node.js

Parsing URL parameters in Node.js enables extraction of query strings and route parameters from HTTP requests for dynamic content and API functionality. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented URL parameter parsing in countless Node.js APIs for filtering, pagination, and data retrieval. From my expertise, the most effective approach is using the built-in URL and URLSearchParams classes for reliable parameter extraction. This method provides native browser-compatible parsing without external dependencies while handling edge cases and encoding automatically.

Use URL and URLSearchParams classes to parse query parameters from request URLs.

import { URL } from 'url'
import http from 'http'

const server = http.createServer((req, res) => {
  // Parse URL with query parameters
  const parsedUrl = new URL(req.url, `http://${req.headers.host}`)
  const params = parsedUrl.searchParams

  // Extract individual parameters
  const page = params.get('page') || 1
  const limit = params.get('limit') || 10
  const search = params.get('search') || ''

  // Get all values for a parameter (for arrays)
  const categories = params.getAll('category')

  // Convert to object
  const queryObject = Object.fromEntries(params.entries())

  // Response with parsed data
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({
    page: parseInt(page),
    limit: parseInt(limit),
    search,
    categories,
    allParams: queryObject
  }))
})

// With Express.js (simpler approach)
import express from 'express'

const app = express()

app.get('/api/products', (req, res) => {
  const { page = 1, limit = 10, search = '', category } = req.query

  res.json({
    page: parseInt(page),
    limit: parseInt(limit),
    search,
    categories: Array.isArray(category) ? category : [category].filter(Boolean)
  })
})

server.listen(3000)

The URL constructor parses the complete URL while URLSearchParams provides methods for query parameter access. Use get() for single values, getAll() for arrays, and Object.fromEntries() to convert all parameters to an object. Express.js provides req.query for automatic parameter parsing.

Best Practice Note:

This is the same URL parameter parsing approach we use in CoreUI backend services for API endpoints. Always validate and sanitize parsed parameters, provide default values for optional parameters, and handle type conversion explicitly for robust API behavior.


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