Middleware

Middleware in Foxx refers to functions that can be mounted like routes and canmanipulate the request and response objects before and after the route itselfis invoked. They can also be used to control access or to provide common logiclike logging etc. Unlike routes, middleware is mounted with the use methodlike a router.

Instead of a function the use method can also accept an object with aregister function that will take a parameter endpoint, the middleware willbe mounted at and returns the actual middleware function. This allowsmanipulating the endpoint before creating the middleware (e.g. to documentheaders, request bodies, path parameters or query parameters).

Examples

Restrict access to ArangoDB-authenticated users:

  1. module.context.use(function (req, res, next) {
  2. if (!req.arangoUser) {
  3. res.throw(401, 'Not authenticated with ArangoDB');
  4. }
  5. next();
  6. });

Any truthy argument passed to the next function will be thrown as an error:

  1. module.context.use(function (req, res, next) {
  2. let err = null;
  3. if (!req.arangoUser) {
  4. err = new Error('This should never happen');
  5. }
  6. next(err); // throws if the error was set
  7. })

Trivial logging middleware:

  1. module.context.use(function (req, res, next) {
  2. const start = Date.now();
  3. try {
  4. next();
  5. } finally {
  6. console.log(`Handled request in ${Date.now() - start}ms`);
  7. }
  8. });

More complex example for header-based sessions:

  1. const sessions = module.context.collection('sessions');
  2. module.context.use({
  3. register (endpoint) {
  4. endpoint.header('x-session-id', joi.string().optional(), 'The session ID.');
  5. return function (req, res, next) {
  6. const sid = req.get('x-session-id');
  7. if (sid) {
  8. try {
  9. req.session = sessions.document(sid);
  10. } catch (e) {
  11. delete req.headers['x-session-id'];
  12. }
  13. }
  14. next();
  15. if (req.session) {
  16. if (req.session._rev) {
  17. sessions.replace(req.session, req.session);
  18. res.set('x-session-id', req.session._key);
  19. } else {
  20. const meta = sessions.save(req.session);
  21. res.set('x-session-id', meta._key);
  22. }
  23. }
  24. };
  25. }
  26. });