User routes

The user routes defined in the user.routes.js file will use express.Router() to declare the route paths with relevant HTTP methods, and assign the corresponding controller function that should be called when these requests are received by the server.

We will keep the user routes simple, by using the following:

  • /api/users for:
    • Listing users with GET
    • Creating a new user with POST
  • /api/users/:userId for:
    • Fetching a user with GET
    • Updating a user with PUT
    • Deleting a user with DELETE

The resulting user.routes.js code will look as follows (without the auth considerations that need to be added for protected routes).

mern-skeleton/server/routes/user.routes.js:

import express from 'express'
import userCtrl from '../controllers/user.controller'

const router = express.Router()

router.route('/api/users')
.get(userCtrl.list)
.post(userCtrl.create)

router.route('/api/users/:userId')
.get(userCtrl.read)
.put(userCtrl.update)
.delete(userCtrl.remove)

router.param('userId', userCtrl.userByID)

export default router