# middleware(config)

It returns a connect (opens new window) middleware used by several Node.js web frameworks such as Express (opens new window).

# Type signature

function middleware(config: MiddlewareConfig): Middleware

The types of MiddlewareConfig and Middleware are like below.

interface MiddlewareConfig {
  channelAccessToken?: string;
  channelSecret: string;

type Middleware =
  ( req: http.IncomingMessage
  , res: http.ServerResponse
  , next: (err?: Error) => void
  ) => void

The Middleware type is defined according to the connect middleware itself. For the detail of the connect middleware, please refer to the connect (opens new window) documentation.

# Usage

A very simple example of the middleware usage with an Express app is like below:

// globally

// or directly with handler
app.post('/webhook', middleware(config), (req, res) => {
  req.body.events // webhook event objects
  req.body.destination // user ID of the bot (optional)

The middleware returned by middleware() parses body and checks signature validation, so you do not need to use validateSignature() directly.

You do not need to use body-parser (opens new window) to parse webhook events, as middleware() embeds body-parser and parses them to objects. Please keep in mind that it will not process requests without X-Line-Signature header. If you have a reason to use body-parser for other routes, please do not use it before the LINE middleware. body-parser parses the request body up and the LINE middleware cannot parse it afterwards.

// don't

// do

There are environments where req.body is pre-parsed, such as Firebase Cloud Functions (opens new window). If it parses the body into string or buffer, do not worry as the middleware will work just fine. If the pre-parsed body is an object, please use validateSignature() manually with the raw body.

About building webhook server, please refer to Webhook.