How to Respond with JSON in Node.js Server
As the creator of CoreUI and with over 25 years of software development experience, I’ll show you how to properly send JSON responses from a Node.js server.
You can send JSON responses in Node.js by setting the Content-Type header to ‘application/json’ and using JSON.stringify() to convert objects to JSON strings.
const http = require('http')
const server = http.createServer((req, res) => {
// Set the response headers
res.setHeader('Content-Type', 'application/json')
res.setHeader('Access-Control-Allow-Origin', '*')
if (req.method === 'GET' && req.url === '/api/users') {
const users = [
{ id: 1, name: 'John Doe', email: '[email protected]' },
{ id: 2, name: 'Jane Smith', email: '[email protected]' }
]
res.statusCode = 200
res.end(JSON.stringify({
success: true,
data: users,
message: 'Users fetched successfully'
}))
} else if (req.method === 'POST' && req.url === '/api/users') {
// Handle POST request with JSON response
res.statusCode = 201
res.end(JSON.stringify({
success: true,
data: { id: 3, name: 'New User' },
message: 'User created successfully'
}))
} else {
// Handle 404 with JSON error response
res.statusCode = 404
res.end(JSON.stringify({
success: false,
error: 'Endpoint not found',
message: 'The requested resource does not exist'
}))
}
})
server.listen(3000, () => {
console.log('Server running on port 3000')
})
The key steps are setting the ‘Content-Type’ header to ‘application/json’, using JSON.stringify() to convert JavaScript objects to JSON strings, and calling res.end() with the JSON string. Always include proper status codes (200 for success, 201 for created, 404 for not found, etc.) and consider adding CORS headers for cross-origin requests. Structure your JSON responses consistently with fields like success, data, message, and error for better API usability.
Best Practice Note:
In CoreUI backend projects, we always structure JSON responses with consistent schemas and proper error handling. This approach ensures reliable communication between our frontend components and API endpoints, making development and debugging much more efficient.



