Express error if agency not found middleware
I managed to accomplish this by adding the agency to res.locals. Here's the amended code:

// /routes/v1/index.js

const router = require("express-promise-router")()

router.use(["/agencies/:id", "/agencies/:id/*"], agencies.addAgencyToResLocals, agencies.ensureUserIsMember)

router
  .route("/agencies/:id")
  .get(agencies.getById)
  .patch(agencies.ensureUserIsAdmin, agencies.patch)
  .delete(agencies.ensureUserIsAdmin, agencies.delete)


// /controllers/v1/agencies/addAgencyToResLocals.js

import db from "../../../db"
import { AgencyDoesNotExistError } from "../../../errors"

export default async (req, res, next) =&gt; {
  const agency = await db.agency.getById(req.params.id)

  if (!agency) throw new AgencyDoesNotExistError()

  res.locals.agency = agency

  next()
}


// /controllers/v1/agencies/ensureUserIsMember.js

import { UnauthorizedError } from "../../../errors"

export default (req, res, next) =&gt; {
  const { agency } = res.locals

  const isMember = agency.members.find(member =&gt; member.authId === req.user.sub)

  if (!isMember) throw new UnauthorizedError()

  next()
}



// /controllers/v1/agencies/getById.js

export default async (req, res) =&gt; res.send(res.locals.agency)


I'm not sure if this is the best solution but it simplifies my code a lot. The one issue I see is that another person working with the code base for the first time would have to have knowledge about the middleware being applied. That being said I feel it's acceptable to say that someone working with express should have knowledge of middleware and how it works IMO.