How to create routes in Express
Creating routes in Express defines how your application responds to different HTTP requests and URL endpoints, forming the backbone of RESTful APIs and web applications.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented countless Express routes for backend APIs and web services.
From my 25 years of experience in web development and 11 years with Node.js, the most effective approach is to use Express application methods that correspond to HTTP verbs like get, post, put, and delete.
This pattern provides clear, RESTful API design and intuitive request handling.
Use Express app methods like app.get(), app.post(), app.put(), and app.delete() to define routes for different HTTP operations.
const express = require('express')
const app = express()
app.use(express.json())
// GET route - retrieve data
app.get('/api/users', (req, res) => {
res.json({ users: ['John', 'Jane', 'Bob'] })
})
// GET route with parameters
app.get('/api/users/:id', (req, res) => {
const userId = req.params.id
res.json({ id: userId, name: 'John Doe' })
})
// POST route - create new data
app.post('/api/users', (req, res) => {
const { name, email } = req.body
res.status(201).json({ id: 123, name, email })
})
// PUT route - update existing data
app.put('/api/users/:id', (req, res) => {
const userId = req.params.id
const { name, email } = req.body
res.json({ id: userId, name, email, updated: true })
})
// DELETE route - remove data
app.delete('/api/users/:id', (req, res) => {
const userId = req.params.id
res.json({ message: `User ${userId} deleted` })
})
app.listen(3000, () => {
console.log('Server running on port 3000')
})
Each HTTP method corresponds to a specific Express method: app.get() for retrieving data, app.post() for creating resources, app.put() for updating resources, and app.delete() for removing resources. Route parameters like :id capture dynamic URL segments accessible via req.params. Request bodies are available through req.body when using express.json() middleware. Response methods like res.json() and res.status() control the HTTP response format and status codes.
This is the same RESTful routing pattern we use in CoreUI backend services to create consistent and predictable API endpoints.
For complex applications, consider using express.Router() to organize routes into separate modules and maintain clean code architecture as your API grows.



