express-routing
Express.js routing patterns and organization
What this skill does
# Express Routing Skill
Patterns for organizing routes in Express.js applications.
## Basic Routing
### Route Methods
```typescript
import express from 'express'
const app = express()
// HTTP methods
app.get('/users', (req, res) => { ... })
app.post('/users', (req, res) => { ... })
app.put('/users/:id', (req, res) => { ... })
app.patch('/users/:id', (req, res) => { ... })
app.delete('/users/:id', (req, res) => { ... })
// All methods
app.all('/secret', (req, res) => { ... })
```
### Route Parameters
```typescript
// Simple parameter
app.get('/users/:id', (req, res) => {
const { id } = req.params
res.json({ userId: id })
})
// Multiple parameters
app.get('/users/:userId/posts/:postId', (req, res) => {
const { userId, postId } = req.params
res.json({ userId, postId })
})
// Optional parameter
app.get('/users/:id?', (req, res) => {
if (req.params.id) {
// Specific user
} else {
// All users
}
})
// Regex constraint
app.get('/users/:id(\\d+)', (req, res) => {
// Only matches numeric IDs
})
```
### Query Parameters
```typescript
app.get('/search', (req, res) => {
const { q, page = '1', limit = '10' } = req.query
const pageNum = parseInt(page as string)
const limitNum = parseInt(limit as string)
res.json({ query: q, page: pageNum, limit: limitNum })
})
```
## Router Organization
### Modular Routers
```typescript
// routes/users.ts
import { Router } from 'express'
const router = Router()
router.get('/', getAllUsers)
router.get('/:id', getUserById)
router.post('/', createUser)
router.put('/:id', updateUser)
router.delete('/:id', deleteUser)
export default router
// routes/index.ts
import { Router } from 'express'
import usersRouter from './users'
import postsRouter from './posts'
import authRouter from './auth'
const router = Router()
router.use('/users', usersRouter)
router.use('/posts', postsRouter)
router.use('/auth', authRouter)
export default router
// app.ts
import routes from './routes'
app.use('/api/v1', routes)
```
### Route Grouping
```typescript
// routes/admin/index.ts
import { Router } from 'express'
import { requireAdmin } from '../../middleware/auth'
const router = Router()
// All admin routes require admin role
router.use(requireAdmin)
router.use('/users', adminUsersRouter)
router.use('/settings', adminSettingsRouter)
router.use('/logs', adminLogsRouter)
export default router
```
### Versioned API
```typescript
// routes/v1/index.ts
const v1Router = Router()
v1Router.use('/users', v1UsersRouter)
v1Router.use('/posts', v1PostsRouter)
// routes/v2/index.ts
const v2Router = Router()
v2Router.use('/users', v2UsersRouter) // New user endpoints
v2Router.use('/posts', v2PostsRouter)
// app.ts
app.use('/api/v1', v1Router)
app.use('/api/v2', v2Router)
```
## RESTful Patterns
### Resource Routes
```typescript
// routes/posts.ts
import { Router } from 'express'
import * as controller from '../controllers/posts'
import { authenticate } from '../middleware/auth'
import { validatePost } from '../middleware/validation'
const router = Router()
// GET /posts - List all posts
router.get('/', controller.index)
// GET /posts/:id - Get single post
router.get('/:id', controller.show)
// POST /posts - Create post
router.post('/', authenticate, validatePost, controller.create)
// PUT /posts/:id - Update post
router.put('/:id', authenticate, validatePost, controller.update)
// DELETE /posts/:id - Delete post
router.delete('/:id', authenticate, controller.destroy)
export default router
```
### Nested Resources
```typescript
// routes/posts.ts
const router = Router()
// Posts
router.get('/', getAllPosts)
router.get('/:postId', getPost)
// Nested comments
router.get('/:postId/comments', getPostComments)
router.post('/:postId/comments', createComment)
router.delete('/:postId/comments/:commentId', deleteComment)
// Alternative: Separate router
const commentsRouter = Router({ mergeParams: true })
commentsRouter.get('/', getPostComments)
commentsRouter.post('/', createComment)
commentsRouter.delete('/:commentId', deleteComment)
router.use('/:postId/comments', commentsRouter)
```
## Controller Pattern
### Basic Controller
```typescript
// controllers/users.ts
import { Request, Response, NextFunction } from 'express'
import * as userService from '../services/users'
export async function index(req: Request, res: Response, next: NextFunction) {
try {
const users = await userService.findAll()
res.json({ data: users })
} catch (error) {
next(error)
}
}
export async function show(req: Request, res: Response, next: NextFunction) {
try {
const user = await userService.findById(req.params.id)
if (!user) {
return res.status(404).json({ error: 'User not found' })
}
res.json({ data: user })
} catch (error) {
next(error)
}
}
export async function create(req: Request, res: Response, next: NextFunction) {
try {
const user = await userService.create(req.body)
res.status(201).json({ data: user })
} catch (error) {
next(error)
}
}
export async function update(req: Request, res: Response, next: NextFunction) {
try {
const user = await userService.update(req.params.id, req.body)
if (!user) {
return res.status(404).json({ error: 'User not found' })
}
res.json({ data: user })
} catch (error) {
next(error)
}
}
export async function destroy(req: Request, res: Response, next: NextFunction) {
try {
await userService.remove(req.params.id)
res.status(204).send()
} catch (error) {
next(error)
}
}
```
### Class-Based Controller
```typescript
// controllers/UserController.ts
import { Request, Response, NextFunction } from 'express'
import { UserService } from '../services/UserService'
export class UserController {
constructor(private userService: UserService) {}
index = async (req: Request, res: Response, next: NextFunction) => {
try {
const users = await this.userService.findAll()
res.json({ data: users })
} catch (error) {
next(error)
}
}
show = async (req: Request, res: Response, next: NextFunction) => {
try {
const user = await this.userService.findById(req.params.id)
res.json({ data: user })
} catch (error) {
next(error)
}
}
// ... other methods
}
// routes/users.ts
const userService = new UserService()
const controller = new UserController(userService)
router.get('/', controller.index)
router.get('/:id', controller.show)
```
## Route Chaining
```typescript
router.route('/users/:id')
.get(getUser)
.put(updateUser)
.delete(deleteUser)
router.route('/posts')
.get(listPosts)
.post(authenticate, validatePost, createPost)
```
## Middleware per Route
```typescript
// Multiple middleware for single route
router.post('/upload',
authenticate,
upload.single('file'),
validateFile,
handleUpload
)
// Array of middleware
const createUserMiddleware = [
authenticate,
validateBody(createUserSchema),
checkPermissions('users:create'),
]
router.post('/users', createUserMiddleware, createUser)
```
## Integration
Used by:
- `backend-developer` agent
- `fullstack-developer` agent
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.