| 1 | import statsd from '../lib/statsd.js' |
| 2 | |
| 3 | export default function abort(req, res, next) { |
| 4 | // If the client aborts the connection, send an error |
| 5 | req.once('aborted', () => { |
| 6 | // ignore aborts from next, usually has to do with webpack-hmr |
| 7 | if (req.path.startsWith('/_next')) { |
| 8 | return |
| 9 | } |
| 10 | // NOTE: Node.js will also automatically set `req.aborted = true` |
| 11 | |
| 12 | const incrementTags = [] |
| 13 | // Be careful with depending on attributes set on the `req` because |
| 14 | // under certain conditions the contextualizers might not yet have |
| 15 | // had a chance to run. |
| 16 | if (req.pagePath) { |
| 17 | incrementTags.push(`path:${req.pagePath}`) |
| 18 | } |
| 19 | if (req.context?.currentCategory) { |
| 20 | incrementTags.push(`product:${req.context.currentCategory}`) |
| 21 | } |
| 22 | statsd.increment('middleware.abort', 1, incrementTags) |
| 23 | |
| 24 | const abortError = new Error('Client closed request') |
| 25 | abortError.statusCode = 499 |
| 26 | abortError.code = 'ECONNRESET' |
| 27 | |
| 28 | // Pass the error to the Express error handler |
| 29 | return next(abortError) |
| 30 | }) |
| 31 | |
| 32 | return next() |
| 33 | } |