Skip to content

Instantly share code, notes, and snippets.

@hilleer
Last active October 7, 2020 14:07
Show Gist options
  • Save hilleer/81600a2686895eb5f434b2faec1e9033 to your computer and use it in GitHub Desktop.
Save hilleer/81600a2686895eb5f434b2faec1e9033 to your computer and use it in GitHub Desktop.
Express middleware
const express = require('express');
const createHttpError = require('http-errors');
const app = express();
app.get('/foo',
middlewareOne,
middlewareTwo,
fooHandler
);
// should come after all other route handlers
app.use(errorHandler);
app.listen(3000, () => console.log('listening'));
function middlewareOne(req, res, next) {
console.log('hit middleware one');
const secretHeader = req.get('x-secret-header');
if (secretHeader !== 'valid-value') {
res.status(403).end();
// important
return;
}
next();
}
function middlewareTwo(req, res, next) {
console.log('hit middleware two');
const { id
} = req.body;
const isValidId = (id) => typeof id === 'string';
if (!isValidId(id)) {
res.status(400).json({
message: 'bad id'
});
// important
return;
}
next();
}
function fooHandler(req, res, next) {
try {
// do some logic that might throw
} catch (error) {
next(error); // forward error to error handler
}
}
function errorHandler(err, req, res, next) {
const httpError = createHttpError(err);
const { status
} = httpError;
res.status(status).json(httpError);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment