How to respond with JSON in Node.js server

Responding with JSON from Node.js servers enables API development and data exchange between client and server applications with proper content formatting. As the creator of CoreUI, a widely used open-source UI library, I’ve built countless Node.js APIs that serve JSON responses for frontend applications and data integrations. From my expertise, the most effective approach is using Express.js res.json() method for automatic JSON serialization and proper headers. This method ensures correct content-type headers and handles JSON conversion seamlessly for reliable API responses.

Use res.json() method to send JSON responses with proper headers and serialization.

// With Express.js (recommended)
import express from 'express'

let app = express()

app.get('/api/users', (req, res) => {
  let users = [
    { id: 1, name: 'John Doe', email: '[email protected]' },
    { id: 2, name: 'Jane Smith', email: '[email protected]' }
  ]

  res.json(users)
})

app.get('/api/user/:id', (req, res) => {
  let user = { id: req.params.id, name: 'John Doe' }
  res.status(200).json({ success: true, data: user })
})

// With built-in http module
import http from 'http'

let server = http.createServer((req, res) => {
  let data = { message: 'Hello World', timestamp: new Date() }

  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify(data))
})

server.listen(3000)

The res.json() method automatically sets the Content-Type header to ‘application/json’ and serializes JavaScript objects to JSON strings. With the built-in http module, manually set headers and use JSON.stringify() to convert objects to JSON format before sending the response.

Best Practice Note:

This is the same JSON response approach we use in CoreUI backend services for consistent API development. Always handle errors gracefully and include status codes with your JSON responses for proper API design.


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