⚡
light
  • light
  • guides
    • getting started
    • server vs serverless
    • routes
    • models
    • factories
    • routing
    • plugins
    • middleware
    • query
    • params
    • global
    • error handling
    • hot module reloading (TODO)
    • databases (TODO)
      • mongoose
      • objection/knex
    • testing (TODO)
      • ava
      • jest
    • deployments (TODO)
      • runkit
      • aws
      • now
      • heroku
      • server
      • google cloud
      • azure
      • netlify
    • misc (TODO)
      • apollo/graphql
  • api
    • server({ routes, opts }): object
    • params(path, url): Promise<object>
    • boom
      • Coming soon
    • micro
      • Coming soon
      • Coming soon
      • Coming soon
      • Coming soon
      • Coming soon
      • Coming soon
Powered by GitBook
On this page
  • Introduction
  • Usage
  • Express and Koa Support

Was this helpful?

  1. guides

middleware

Introduction

Middleware is code that is run before a route. It can add things onto the req and res objects to pass to the main handler or simply return the request early. The idea is very similar to how Express and Koa middleware work but they are not compatible by default.

Usage

A middleware is an async function which accepts the req, and res objects.

const { send } = require('light');

const checkAuth = async (req, res) => {
  if (!req.headers.authorization) {
    return send(401, 'please include authorization header');
  }
  return req.isAuthenticated = true;
}

To include middleware in your route, simply call the middleware function.

const { createRoute } = require('light');

const { route, addMiddleware } = route('middleware');

addMiddleware(checkAuth, someOtherMiddleare);
addMiddleware(whoopsForgotOne);

module.exports = route((req) => {
  return {
    isAuthenticated: req.isAuthenticated,
  };
});

Express and Koa Support

PreviouspluginsNextquery

Last updated 5 years ago

Was this helpful?

We are experimenting with adding wrappers to add partial support for Express and Koa! See this for more information.

GitHub issue