Coding Hub  /  Reference  /  Node unit

secure rest apis

Everything between "my routes work" and "I would put this on the internet": who you are, what you may touch, and what happens when it goes wrong. Use the filter to jump straight to what you need.

Part one: the surface

Before a single route is written, decide what the API promises. Every decision here is one you will be living with when there are forty endpoints and you cannot remember why the odd one out is odd.

01 What REST actually commits you to

REST is not a library you install. It is an agreement about how URLs and HTTP verbs line up, and the whole value of it is that someone who has never seen your code can guess your endpoints correctly.

The agreement is short. A URL names a thing (a noun, plural). The verb says what you are doing to it. The verb is never in the URL.

Once you hold that line, the table on the right writes itself for every resource you ever add — plants, users, orders, anything.

POST /createPlant and GET /deletePlant?id=3 both work, and both throw the agreement away. A GET must never change data: browsers, proxies and crawlers all assume they can replay a GET safely.

the whole agreement
GET    /api/plants        list them
POST   /api/plants        create one
GET    /api/plants/:id    read that one
PATCH  /api/plants/:id    change part of that one
DELETE /api/plants/:id    remove that one

# the verb carries the action, so the URL never does
POST   /api/plants/createPlant      <- wrong
GET    /api/plants/delete?id=3      <- wrong, and dangerous
verb properties worth knowing
VerbSafeIdempotentMeans
GETyesyesnever changes anything
POSTnonotwice creates two
PATCHnono*partial change
PUTnoyesreplace whole record
DELETEnoyesgone stays gone

02 Status codes that mean something

The status code is the first thing a client reads, and for a lot of clients it is the only thing they read before deciding whether to show an error. Returning 200 with { error: ... } in the body means every caller has to parse the body to find out it failed.

You need about eight codes. Learn these and you have covered almost every case you will hit.

The split that matters: 4xx is the caller's fault and they can fix it by sending something different. 5xx is your fault and the same request would have worked if your code were correct.

the eight that cover almost everything
CodeNameUse it when
200OKread or update succeeded
201CreatedPOST made a new record
204No Contentdelete succeeded, nothing to return
400Bad Requestbody failed validation
401Unauthorizedno token, or token invalid
403Forbiddenvalid token, but not allowed
404Not Foundno such record
409Conflictduplicate, e.g. email taken
422Unprocessablewell-formed but semantically wrong
500Server Erroryour bug — never send on purpose
401 and 403 are not the same
// 401: I do not know who you are.
//      Fix: log in and send a token.
res.status(401).json({ error: 'Authentication required' })

// 403: I know exactly who you are, and no.
//      Fix: nothing the caller can do. Sending a
//      different token for the same account won't help.
res.status(403).json({ error: 'Admin access required' })

03 One shape for every response

Pick one envelope and never deviate. Clients then write one unwrapping function instead of a special case per endpoint, and a typo in one controller cannot quietly change the contract.

The shape below separates the payload from everything about the payload. Lists get a meta block; single records do not; errors always have error and never have data.

Deciding this on day one costs five minutes. Retrofitting it across thirty endpoints after the front end is written costs a weekend.

the envelope
// one record
{ "data": { "id": "6630...", "name": "Monstera" } }

// a list, with everything the client needs to paginate
{
  "data": [ { "id": "6630...", "name": "Monstera" } ],
  "meta": { "page": 1, "limit": 20, "total": 57, "pages": 3 }
}

// a failure: error present, data absent, always
{
  "error": "Validation failed",
  "details": { "name": "Name is required" }
}

04 The folder structure that scales

Each layer gets one job, and layers only ever call downward. A route knows no database calls. A controller knows no SQL or Mongoose internals beyond the model it calls. A model knows nothing about HTTP — no req, no res, no status codes.

The payoff is testability. A service function that takes plain arguments and returns plain data can be tested without starting a server.

The usual slide is a controller that grows query logic until it is 200 lines. When a controller stops being readable at a glance, the query belongs in the model or a service.

src/
src/
  server.js              start listening, nothing else
  app.js                 build the express app, mount middleware
  config/
    env.js               read + validate process.env once
    db.js                connect to mongo
  models/
    user.model.js        schema, hooks, instance methods
    plant.model.js
  routes/
    index.js             mount all routers under /api
    auth.routes.js
    plant.routes.js
  controller/
    auth.controller.js   req/res in, model calls out
    plant.controller.js
  middleware/
    auth.js              requireAuth, requireRole
    validate.js          body checking
    errorHandler.js      the single funnel
  utils/
    ApiError.js          typed errors
    asyncHandler.js      catches rejected promises
direction of calls
request
   |
   v
route  --> middleware --> controller --> model --> database
                              |
                              v
                          response

# calls only ever go downward.
# a model that imports res has the layers backwards.

Part two: the data layer

The database is the last place a bad value can be stopped, so it is the one place validation must not be optional. Everything above it is a convenience for the caller.

05 The model is your first validator

Put the real constraints in the schema. Not because callers are hostile — though some are — but because a bug in a controller, a script you run at the console, or a future endpoint you have not written yet all go through the model.

required, enum, min, maxlength, match and unique cover most of it. Give each one a message, because the default Mongoose text is not something you want a user to read.

unique: true is not a validator — it builds a database index. It fails with a duplicate-key error (code 11000), not a ValidationError, which is why the error handler later has a special branch for it.

src/models/plant.model.js
const mongoose = require('mongoose')

const plantSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Name is required'],
    trim: true,
    maxlength: [80, 'Name cannot exceed 80 characters']
  },
  location: {
    type: String,
    enum: {
      values: ['indoor', 'outdoor', 'greenhouse'],
      message: '{VALUE} is not a supported location'
    },
    default: 'indoor'
  },
  wateringDays: {
    type: Number,
    min: [1, 'Must be at least 1 day'],
    max: [365, 'Must be 365 days or fewer'],
    default: 7
  },
  // Stamped from the token, never from the request body.
  ownerId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true
  }
}, { timestamps: true })

module.exports = mongoose.model('Plant', plantSchema)

Watch the braces in enum. message: '{VALUE is not supported' — a missing closing brace — is valid JavaScript, so nothing warns you, and Mongoose silently stops substituting the value.

06 Validating input at the edge

Schema validation runs when you save. That is late: you have already built an object, and the error you get back is shaped for you, not for the caller. A small middleware that checks the body first gives a clean 400 with every problem at once.

Returning all the errors matters more than it sounds. An API that reports one missing field per request turns a five-field form into five round trips.

src/middleware/validate.js
const ApiError = require('../utils/ApiError')

// rules: { field: [ [testFn, message], ... ] }
function validate (rules) {
  return (req, res, next) => {
    const details = {}

    for (const [field, checks] of Object.entries(rules)) {
      for (const [test, message] of checks) {
        if (!test(req.body[field], req.body)) {
          details[field] = message
          break            // first failure per field is enough
        }
      }
    }

    if (Object.keys(details).length > 0) {
      return next(ApiError.badRequest('Validation failed', details))
    }
    next()
  }
}

// Reusable predicates.
const required = v => v !== undefined && v !== null && v !== ''
const isString = v => typeof v === 'string'
const maxLen = n => v => v === undefined || String(v).length <= n
const isEmail = v => typeof v === 'string' && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v)
const minLen = n => v => typeof v === 'string' && v.length >= n

module.exports = { validate, required, isString, maxLen, isEmail, minLen }
using it on a route
const { validate, required, maxLen } = require('../middleware/validate')

router.post('/',
  requireAuth,
  validate({
    name: [[required, 'Name is required'],
           [maxLen(80), 'Name cannot exceed 80 characters']]
  }),
  plantController.createPlant
)

07 Mass assignment: the bug that grants admin

This is the single most common way a student API gets taken over, and it does not look like a bug. It looks like clean, concise code.

new User(req.body) builds a user out of whatever the caller sent. If the caller sent {"role": "admin"}, and role is a real field on your schema, they are now an admin. They did not break anything — they used your endpoint exactly as written.

The fix is to never hand the body to a model. Name the fields you accept. Anything you do not name cannot be set, including fields you add to the schema next month.

The same applies to Object.assign(doc, req.body) on update, and to findByIdAndUpdate(id, req.body). All three are the same bug wearing different clothes.

the attack, and the fix
// VULNERABLE -------------------------------------------
exports.signup = async (req, res) => {
  const user = new User(req.body)
  await user.save()
  res.status(201).json({ data: user })
}

// POST /api/auth/signup
// { "email": "a@b.c", "password": "pw", "role": "admin" }
// -> they are an admin. Your code did what you told it.


// SAFE --------------------------------------------------
exports.signup = async (req, res) => {
  // Name every field you are willing to accept.
  const user = new User({
    email: req.body.email,
    password: req.body.password,
    name: req.body.name
    // role is absent, so it falls back to the schema default
  })
  await user.save()
  res.status(201).json({ data: user })
}
a pick() helper, if you prefer
function pick (source, keys) {
  const out = {}
  for (const key of keys) {
    if (source[key] !== undefined) out[key] = source[key]
  }
  return out
}

const CREATABLE = ['name', 'location', 'wateringDays']
const plant = new Plant({
  ...pick(req.body, CREATABLE),
  ownerId: req.user._id        // from the token, never the body
})

Part three: who are you

Authentication answers one question and no others: which account is making this request? Everything about permissions comes later, and mixing the two is how holes appear.

08 Users, and the field you never store

A user document holds a password hash. It never holds a password. Nothing in your system should be able to print one, email one back, or log one.

Two settings do most of the defensive work here. select: false on the hash keeps it out of every query result unless you ask for it explicitly, so it cannot be leaked by a controller that forgets to strip it. role with an enum and a safe default means the only way to become an admin is a deliberate database change.

lowercase: true on email prevents the duplicate-account bug where Sam@x.com and sam@x.com are two people.

src/models/user.model.js
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, 'Email is required'],
    unique: true,
    lowercase: true,
    trim: true,
    match: [/^[^@\s]+@[^@\s]+\.[^@\s]+$/, 'Email is not valid']
  },
  password: {
    type: String,
    required: [true, 'Password is required'],
    minlength: [8, 'Password must be at least 8 characters'],
    select: false          // never comes back from a find()
  },
  name: { type: String, trim: true, maxlength: 80 },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'        // the only safe default
  }
}, { timestamps: true })

module.exports = mongoose.model('User', userSchema)

09 Hashing on save

Hash in a pre('save') hook rather than in the controller. Then it does not matter which code path creates or changes a user — a signup route, a password reset, a seed script — the hash happens.

The isModified guard is the part people miss. Without it, every save of an existing user re-hashes the already-hashed value, and the next login fails with no obvious cause.

Use bcryptjs, not bcrypt. The latter compiles native code and will not install on machines without build tools.

hook and compare method
// Runs before every save. Arrow functions have no `this`,
// so this callback must be a regular function.
userSchema.pre('save', async function (next) {
  // Only hash when the password actually changed.
  if (!this.isModified('password')) return next()

  this.password = await bcrypt.hash(this.password, 10)
  next()
})

// Instance method: user.matchesPassword('guess')
userSchema.methods.matchesPassword = function (plain) {
  return bcrypt.compare(plain, this.password)
}

// Belt and braces: strip the hash from any JSON output,
// even if someone selected it deliberately.
userSchema.methods.toJSON = function () {
  const obj = this.toObject()
  delete obj.password
  return obj
}
why isModified matters
// Without the guard:
user.name = 'New name'
await user.save()
// -> password re-hashed: hash(hash(pw))
// -> every future login fails, and nothing logged an error

10 Signup

Check for the duplicate before you create. You could let the unique index fail and catch error code 11000, and your error handler should still cover that case, but an explicit check gives a clearer 409.

Note what is not here: no role from the body, no token fields, no _id. Only the three things a new account legitimately supplies.

src/controller/auth.controller.js
const User = require('../models/user.model')
const ApiError = require('../utils/ApiError')
const asyncHandler = require('../utils/asyncHandler')
const { signToken } = require('../utils/jwt')

exports.signup = asyncHandler(async (req, res) => {
  const { email, password, name } = req.body

  const existing = await User.findOne({ email: email.toLowerCase() })
  if (existing) {
    throw ApiError.conflict('That email is already registered')
  }

  // Named fields only. role is never read from the body.
  const user = await User.create({ email, password, name })

  res.status(201).json({
    data: {
      user: { id: user._id, email: user.email, role: user.role },
      token: signToken(user)
    }
  })
})

11 Login, and issuing a token

The password field is select: false, so you have to ask for it with .select('+password'). Forgetting this gives a confusing bug: user.password is undefined, bcrypt.compare rejects, and every login fails even with the right password.

Give the same message for an unknown email and a wrong password. Different messages let anyone test which email addresses have accounts on your system.

Never put anything secret in a token. The payload is base64, not encryption — anyone can read it. Put the user id and the role in; put nothing else.

login
exports.login = asyncHandler(async (req, res) => {
  const { email, password } = req.body

  // +password because the schema hides it by default.
  const user = await User.findOne({ email: email.toLowerCase() })
                         .select('+password')

  // One message for both failures, so the endpoint cannot
  // be used to discover which emails are registered.
  if (!user || !(await user.matchesPassword(password))) {
    throw ApiError.unauthorized('Email or password is incorrect')
  }

  res.json({
    data: {
      user: { id: user._id, email: user.email, role: user.role },
      token: signToken(user)
    }
  })
})
src/utils/jwt.js
const jwt = require('jsonwebtoken')
const { JWT_SECRET, JWT_EXPIRES_IN } = require('../config/env')

function signToken (user) {
  return jwt.sign(
    { sub: String(user._id), role: user.role },   // payload: public
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN }                  // e.g. '7d'
  )
}

function verifyToken (token) {
  return jwt.verify(token, JWT_SECRET)   // throws if bad or expired
}

module.exports = { signToken, verifyToken }

12 requireAuth: proving who you are

This middleware does three things in order: pull the token out of the header, verify the signature, and load the live user. The third step is the one people skip, and skipping it is why deleted or demoted accounts keep working until their token expires.

Attach the user document to req.user, not the raw token payload. If you attach the payload, req.user._id is undefined — the field is called sub — and every ownership check silently compares against nothing.

A token payload is not a user. req.user = decoded is the single most common cause of records saving with ownerId: null and no error anywhere.

src/middleware/auth.js
const User = require('../models/user.model')
const ApiError = require('../utils/ApiError')
const asyncHandler = require('../utils/asyncHandler')
const { verifyToken } = require('../utils/jwt')

const requireAuth = asyncHandler(async (req, res, next) => {
  // 1. Pull it out of: Authorization: Bearer <token>
  const header = req.headers.authorization || ''
  if (!header.startsWith('Bearer ')) {
    throw ApiError.unauthorized('Authentication required')
  }
  const token = header.slice(7).trim()

  // 2. Verify the signature and expiry.
  let payload
  try {
    payload = verifyToken(token)
  } catch (err) {
    // Say which, so a client knows whether to refresh or re-login.
    throw ApiError.unauthorized(
      err.name === 'TokenExpiredError' ? 'Token expired' : 'Token is invalid'
    )
  }

  // 3. Load the live user. Catches deleted accounts and
  //    role changes made since the token was issued.
  const user = await User.findById(payload.sub)
  if (!user) throw ApiError.unauthorized('Account no longer exists')

  req.user = user          // the document, not the payload
  next()
})

module.exports = { requireAuth }
the bug this prevents
// WRONG
req.user = payload
req.user._id      // undefined - the field is `sub`
// -> ownerId: null on every created record, no error

// RIGHT
req.user = await User.findById(payload.sub)
req.user._id      // a real ObjectId
req.user.role     // current role, not the one in the token

Part four: what may you do

Authorization is a separate question from identity, and it has two layers that are easy to confuse: what your role lets you do in general, and whether this particular record is yours.

13 Role checks

A role check is coarse: it asks whether this kind of user may use this kind of endpoint at all. It cannot answer whether a specific record belongs to them — that is the next entry.

Write it as a factory so the route reads like a sentence, and always put it after requireAuth. On its own it would read req.user before anything has set it.

requireRole
// Usage: requireRole('admin') or requireRole('admin', 'moderator')
function requireRole (...allowed) {
  return (req, res, next) => {
    // Guard against being mounted without requireAuth in front.
    if (!req.user) {
      return next(ApiError.unauthorized('Authentication required'))
    }
    if (!allowed.includes(req.user.role)) {
      // 403, not 401: we know who they are, they just may not.
      return next(ApiError.forbidden('Admin access required'))
    }
    next()
  }
}

module.exports = { requireAuth, requireRole }
on a route
// order matters: identity first, then permission
router.get('/users',
  requireAuth,
  requireRole('admin'),
  adminController.listUsers
)

14 Ownership: the record-level check

Role checks let a user reach the endpoint. They do not stop user A editing user B's plant — both are logged-in users hitting the same route. That check can only happen after you have loaded the record, because until then you do not know who owns it.

Do it in one place. A helper that every controller calls is far harder to forget than four copies of the same if.

Admins pass the ownership check by rule, which is usually what you want: an admin fixing a student's record should not be blocked by it.

the check
// ObjectId !== string, so compare as strings.
function ownsOrAdmin (user, doc) {
  if (user.role === 'admin') return true
  return String(doc.ownerId) === String(user._id)
}

// In a controller, after loading:
const plant = await Plant.findById(req.params.id)
if (!plant) throw ApiError.notFound('Plant not found')
if (!ownsOrAdmin(req.user, plant)) {
  throw ApiError.forbidden('You do not own this plant')
}

plant.ownerId === req.user._id is always false. Both are ObjectId objects, and === compares identity, not value. Wrap both in String(), or use .equals().

15 Filter by owner, do not fetch then reject

For list endpoints there is a better move than loading everything and filtering afterwards: put the owner into the query. The database never returns rows the caller may not see, which is faster and removes a whole class of leak.

This also means an ordinary user asking for page 2 gets page 2 of their own records, with a correct total. Filtering after pagination gives short pages and a wrong count.

scope the query, not the result
// Admins see everything; everyone else sees their own.
const scope = req.user.role === 'admin'
  ? {}
  : { ownerId: req.user._id }

const [items, total] = await Promise.all([
  Plant.find(scope).skip(skip).limit(limit).sort(sort),
  Plant.countDocuments(scope)
])
the wrong way
// Loads every plant in the database into memory,
// then throws most of them away. Page counts are wrong,
// and one slow day it falls over.
const all = await Plant.find().skip(skip).limit(limit)
const mine = all.filter(p => String(p.ownerId) === String(req.user._id))

16 When 404 is the better answer than 403

Returning 403 Forbidden for a record that exists but is not yours confirms that it exists. For most apps that is harmless. For anything where the identifiers are guessable or the existence of a record is itself private, it is a leak.

The alternative is to answer 404 for both cases: not found, and found but not yours. The caller cannot tell the difference, which is the point.

Pick one policy and apply it everywhere. A mixed API, where some endpoints 403 and others 404, leaks exactly the information you were trying to hide.

which to send
SituationLeakyPrivate
No such record404404
Exists, not yours403404
Exists, yours200200

Part five: full CRUD

Five endpoints, each with the same three concerns: is the input acceptable, is this caller allowed, and what exactly goes back.

17 Create

Three things make a create endpoint correct. Accept only named fields. Stamp the owner from the token. Return 201 with the created record, so the client does not have to re-fetch to learn the generated id.

The guard at the top is worth keeping even once the route is right. If anyone ever mounts this controller without requireAuth, it fails immediately with a clear message instead of writing records with a null owner.

createPlant
const CREATABLE = ['name', 'location', 'wateringDays']

exports.createPlant = asyncHandler(async (req, res) => {
  // Fails loudly if this route lost its requireAuth.
  if (!req.user || !req.user._id) {
    throw ApiError.unauthorized('Authentication required')
  }

  const plant = await Plant.create({
    ...pick(req.body, CREATABLE),
    ownerId: req.user._id        // from the token, never the body
  })

  res.status(201).json({ data: plant })
})

18 Read one

Load, check it exists, check the caller may see it, return it. The order matters: you cannot run the ownership check before the record is in hand.

An id that is not a valid ObjectId makes findById throw a CastError rather than return null. Let it reach the error handler, which turns it into a 400.

getPlant
exports.getPlant = asyncHandler(async (req, res) => {
  const plant = await Plant.findById(req.params.id)

  if (!plant) throw ApiError.notFound('Plant not found')

  if (!ownsOrAdmin(req.user, plant)) {
    throw ApiError.forbidden('You do not own this plant')
  }

  res.json({ data: plant })
})

19 Read many: pagination, filtering, sorting

This is the endpoint that gets slow first, and the one most often left unbounded. Three rules keep it safe: always cap the page size, always whitelist what may be sorted on, and always run the count against the same filter as the query.

The sort whitelist is not fussiness. sort(req.query.sort) lets a caller sort on any field, including unindexed ones, which is a cheap way to make your database do expensive work.

limit straight from the query string means ?limit=1000000 is a valid request. Clamp it.

listPlants
const SORTABLE = ['name', 'createdAt', 'wateringDays']
const MAX_LIMIT = 100

exports.listPlants = asyncHandler(async (req, res) => {
  // --- paging, clamped -------------------------------
  const page  = Math.max(1, parseInt(req.query.page, 10) || 1)
  const limit = Math.min(MAX_LIMIT,
                Math.max(1, parseInt(req.query.limit, 10) || 20))
  const skip  = (page - 1) * limit

  // --- filter: start from the caller's scope ---------
  const filter = req.user.role === 'admin' ? {} : { ownerId: req.user._id }

  if (req.query.location) filter.location = req.query.location
  if (req.query.q) {
    // Escape user input before it becomes a regex.
    const safe = String(req.query.q).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    filter.name = new RegExp(safe, 'i')
  }

  // --- sort: whitelist only --------------------------
  let sort = { createdAt: -1 }
  if (req.query.sort) {
    const desc  = req.query.sort.startsWith('-')
    const field = desc ? req.query.sort.slice(1) : req.query.sort
    if (SORTABLE.includes(field)) sort = { [field]: desc ? -1 : 1 }
  }

  const [items, total] = await Promise.all([
    Plant.find(filter).sort(sort).skip(skip).limit(limit),
    Plant.countDocuments(filter)      // same filter, or the count lies
  ])

  res.json({
    data: items,
    meta: { page, limit, total, pages: Math.ceil(total / limit) }
  })
})
query parameters
ParameterExampleEffect
page?page=21-based, defaults to 1
limit?limit=50capped at 100
sort?sort=-createdAt- prefix for descending
location?location=indoorexact match
q?q=ferncase-insensitive name search

20 Update: PATCH, and why not PUT

PATCH changes the fields you send. PUT replaces the whole record, which means any field the client omits should be cleared. Most clients do not expect that, so most APIs offer PATCH and leave PUT alone.

Use runValidators: true if you update through findByIdAndUpdate — schema validators do not run on update by default. The version below loads, mutates and saves instead, which runs validators and any pre('save') hooks, at the cost of one extra query.

updatePlant
const UPDATABLE = ['name', 'location', 'wateringDays']

exports.updatePlant = asyncHandler(async (req, res) => {
  const plant = await Plant.findById(req.params.id)

  if (!plant) throw ApiError.notFound('Plant not found')
  if (!ownsOrAdmin(req.user, plant)) {
    throw ApiError.forbidden('You do not own this plant')
  }

  // Only the whitelist. ownerId and role can never be reassigned.
  for (const field of UPDATABLE) {
    if (req.body[field] !== undefined) plant[field] = req.body[field]
  }

  await plant.save()        // runs validators and pre-save hooks
  res.json({ data: plant })
})
the findByIdAndUpdate trap
// Validators are OFF by default on update.
await Plant.findByIdAndUpdate(id, body)                      // no checks
await Plant.findByIdAndUpdate(id, body, {
  new: true,              // return the updated doc, not the old one
  runValidators: true     // actually enforce the schema
})

// And this is still mass assignment if body is req.body.

21 Delete: hard and soft

A hard delete removes the row. A soft delete sets a flag and leaves it there. Soft deletes are usually right for anything a user can destroy by accident, and they are the only way to answer "what happened to that record" later.

The cost of soft deletes is that every read must exclude them. Miss one query and deleted records reappear. A schema-level query helper keeps that honest.

204 No Content is the conventional response: success, and there is deliberately no body. Do not send { "data": null } with a 200.

hard delete
exports.deletePlant = asyncHandler(async (req, res) => {
  const plant = await Plant.findById(req.params.id)

  if (!plant) throw ApiError.notFound('Plant not found')
  if (!ownsOrAdmin(req.user, plant)) {
    throw ApiError.forbidden('You do not own this plant')
  }

  await plant.deleteOne()
  res.status(204).send()       // no body, by convention
})
soft delete
// 1. the schema gains a flag
const plantSchema = new mongoose.Schema({
  // ...the existing fields
  deletedAt: { type: Date, default: null, index: true }
})

// 2. deleting sets it instead of removing the row
exports.deletePlant = asyncHandler(async (req, res) => {
  const plant = await Plant.findById(req.params.id)
  if (!plant) throw ApiError.notFound('Plant not found')
  if (!ownsOrAdmin(req.user, plant)) {
    throw ApiError.forbidden('You do not own this plant')
  }

  plant.deletedAt = new Date()
  await plant.save()
  res.status(204).send()
})

// 3. and EVERY read must now exclude them
Plant.find({ ...filter, deletedAt: null })

Part six: the rest of the job

What separates an assignment from something you would deploy. None of it is hard; all of it is noticed when missing.

22 Every error through one funnel

Scattered res.status(...).json(...) calls drift apart: different shapes, different wording, and eventually one that leaks a stack trace. Throw a typed error instead and let one handler decide what the client sees.

An Express error handler is identified by having four parameters. Write three and Express treats it as ordinary middleware and never calls it on an error — a genuinely confusing failure, because the code looks right.

Never send err.stack to a client in production. It describes your file layout and dependency versions.

src/utils/ApiError.js
class ApiError extends Error {
  constructor (status, message, details) {
    super(message)
    this.status = status
    this.details = details
    this.isOperational = true    // we threw this on purpose
    Error.captureStackTrace(this, this.constructor)
  }

  static badRequest   (m, d) { return new ApiError(400, m, d) }
  static unauthorized (m)    { return new ApiError(401, m) }
  static forbidden    (m)    { return new ApiError(403, m) }
  static notFound     (m)    { return new ApiError(404, m) }
  static conflict     (m)    { return new ApiError(409, m) }
}

module.exports = ApiError
src/middleware/errorHandler.js
// FOUR parameters. Express checks arity to find this.
function errorHandler (err, req, res, next) {
  let status  = err.status || 500
  let message = err.message || 'Something went wrong'
  let details = err.details

  // Mongoose: bad ObjectId in the URL
  if (err.name === 'CastError') {
    status = 400
    message = `Invalid ${err.path}: ${err.value}`
  }

  // Mongoose: schema validation
  if (err.name === 'ValidationError') {
    status = 400
    message = 'Validation failed'
    details = Object.fromEntries(
      Object.entries(err.errors).map(([k, v]) => [k, v.message])
    )
  }

  // Mongo: unique index violation
  if (err.code === 11000) {
    status = 409
    message = `That ${Object.keys(err.keyValue)[0]} is already taken`
  }

  // Log real failures; never log expected 4xx noise.
  if (status >= 500) console.error(err)

  res.status(status).json({
    error: message,
    ...(details && { details }),
    ...(process.env.NODE_ENV !== 'production' && { stack: err.stack })
  })
}

module.exports = errorHandler

23 Async errors do not throw themselves

An exception inside an async route handler becomes a rejected promise. Express 4 does not watch for that, so the request hangs until it times out — no error, no response, nothing in the log.

A one-function wrapper fixes it everywhere. Express 5 forwards rejections automatically, but wrapping is harmless there and keeps the code portable between the two.

src/utils/asyncHandler.js
// Wraps an async handler so a rejected promise reaches next().
const asyncHandler = fn => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next)

module.exports = asyncHandler
with and without
// Express 4, unwrapped: this request hangs forever.
router.get('/:id', async (req, res) => {
  const plant = await Plant.findById(req.params.id)  // throws
  res.json({ data: plant })
})

// Wrapped: the rejection reaches the error handler.
router.get('/:id', asyncHandler(async (req, res) => {
  const plant = await Plant.findById(req.params.id)
  res.json({ data: plant })
}))

24 Rate limiting, starting with login

Without a limit, an attacker can try passwords as fast as your server answers. bcrypt makes each attempt slow, which helps, but it does not stop a patient script.

Limit the auth routes hard and everything else gently. Keying the login limiter on email as well as IP stops one attacker working through many accounts from behind a single address.

rate limits
const rateLimit = require('express-rate-limit')

// Everything: generous.
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 300,
  standardHeaders: true,
  legacyHeaders: false
})

// Login: strict.
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5,
  skipSuccessfulRequests: true,     // only failures count
  message: { error: 'Too many attempts. Try again in 15 minutes.' }
})

app.use('/api', apiLimiter)
router.post('/login', loginLimiter, authController.login)

25 Helmet, CORS, and secrets

Three lines of setup that are invisible when present and obvious when missing. helmet sets a set of defensive response headers. cors decides which origins may call you — the default of * is for public read-only APIs, not one behind a login.

Secrets come from the environment and are validated at boot. A server that starts with JWT_SECRET undefined will sign tokens with undefined and verify them happily, which is no signature at all.

.env goes in .gitignore before the first commit. A secret that has ever been pushed is burned and must be rotated — deleting it in a later commit does not remove it from the history.

src/app.js
const express = require('express')
const helmet = require('helmet')
const cors = require('cors')

const app = express()

app.use(helmet())
app.use(cors({
  origin: process.env.CLIENT_ORIGIN || 'http://localhost:5173',
  credentials: true
}))
app.use(express.json({ limit: '10kb' }))   // cap the body size

app.use('/api', require('./routes'))
app.use(require('./middleware/notFound'))
app.use(require('./middleware/errorHandler'))   // last, always

module.exports = app
src/config/env.js
require('dotenv').config()

const required = ['MONGODB_URI', 'JWT_SECRET']
const missing = required.filter(k => !process.env[k])

if (missing.length) {
  // Fail at boot, loudly, not at the first request.
  throw new Error(`Missing env vars: ${missing.join(', ')}`)
}

module.exports = {
  PORT: process.env.PORT || 3000,
  MONGODB_URI: process.env.MONGODB_URI,
  JWT_SECRET: process.env.JWT_SECRET,
  JWT_EXPIRES_IN: process.env.JWT_EXPIRES_IN || '7d',
  isProd: process.env.NODE_ENV === 'production'
}

26 Logging you can use at 2am

A log line is only worth writing if it helps you answer a question later. Method, path, status and duration answer most of them. Add a request id and you can follow one request through every line it produced.

Never log the body of a login request, an Authorization header, or a password field. Logs get shipped to third-party services and read by people who should not have credentials.

request logging
const morgan = require('morgan')

// Compact in production, readable in development.
app.use(morgan(isProd ? 'combined' : 'dev'))
redacting, if you roll your own
const REDACT = ['password', 'token', 'authorization']

function safeBody (body) {
  const out = { ...body }
  for (const key of REDACT) {
    if (key in out) out[key] = '[redacted]'
  }
  return out
}

console.log(JSON.stringify({
  method: req.method,
  path: req.originalUrl,
  status: res.statusCode,
  ms: Date.now() - start,
  body: safeBody(req.body)
}))

27 Test the permission matrix, not the happy path

The happy path is the part you already checked by hand. The cases that break in production are the ones nobody thought to try: another user's record, an expired token, a missing token, an admin override.

Write them as a table. Four lines of setup and the matrix tests itself.

supertest
const request = require('supertest')
const app = require('../src/app')

describe('GET /api/plants/:id', () => {
  test('owner gets 200', async () => {
    await request(app).get(`/api/plants/${plantId}`)
      .set('Authorization', `Bearer ${ownerToken}`)
      .expect(200)
  })

  test('other user gets 403', async () => {
    await request(app).get(`/api/plants/${plantId}`)
      .set('Authorization', `Bearer ${otherToken}`)
      .expect(403)
  })

  test('admin gets 200', async () => {
    await request(app).get(`/api/plants/${plantId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200)
  })

  test('no token gets 401', async () => {
    await request(app).get(`/api/plants/${plantId}`).expect(401)
  })

  test('cannot set role at signup', async () => {
    const res = await request(app).post('/api/auth/signup')
      .send({ email: 'x@y.z', password: 'password1', role: 'admin' })
      .expect(201)
    expect(res.body.data.user.role).toBe('user')   // not admin
  })
})

28 Pre-flight checklist

Run down this list before you call an API finished. Every line is something that has gone wrong in a real project.

  • .env is in .gitignore, and was there before the first commit
  • JWT_SECRET is long and random, and the server refuses to boot without it
  • No controller passes req.body straight to a model
  • role cannot be set through signup or update
  • Every protected route has requireAuth, checked by reading the router file
  • Ownership is checked after loading, on read, update and delete
  • List endpoints clamp limit and whitelist sort
  • The error handler takes four parameters
  • Stack traces never reach a production response
  • Login is rate limited
  • Passwords and tokens never appear in logs
  • 404 and the error handler are mounted last, in that order
the finished surface
MethodPathAuthWho
POST/api/auth/signupnoneanyone
POST/api/auth/loginnoneanyone
GET/api/auth/metokenself
GET/api/plantstokenown, or all if admin
POST/api/plantstokenany user
GET/api/plants/:idtokenowner or admin
PATCH/api/plants/:idtokenowner or admin
DELETE/api/plants/:idtokenowner or admin
GET/api/userstokenadmin only

29 Check yourself: the permission matrix

Every combination below is a request someone will eventually make. Pick a role, a token, a record and an endpoint, and the panel shows which guard stops it and what the caller sees.

The decision runs in the same order your middleware does: requireAuth, then requireRole, then the ownership check inside the controller. The first one to object is the one that answers.

The combination worth sitting with is admin + someone else's. It returns 200, and that is deliberate — but it means every admin account is a skeleton key, which is why admin is never the default role.

try it

Role

Token

The record is

Request