Middleware

The request methods of MicroRouter may take a second argument which is the middleware function. You may use existing middlewares such as body-parser, cookie-parse etc.

You can define one like so, similar to express.

Handler Scoped Middleware

The below example shows how to define a middleware for a single request handler. The middleware function secretMiddleware is effective for the url /secret-data only.

*secret-middleware.ts*

...


const secretMiddleware = (req: MicroRequest, res: MicroResponse, next: NextFunction) => {

    const secret = req.headers['authorization']

    if (!secret) {
        res.send(401, 'missing_token')
        return
    }

    if (!/Bearer /.test(secret)) {
        res.send(400, 'token_malformed')
        return
    }

    const token = secret.replace('Bearer ', '')

    // imaginary validation
    const tokenValid = true

    if (!tokenValid) {
        res.send(401, 'invalid_token')
        return
    }

    next()

    // or you can overwrite the request to be passed on to the next handler
    // req.user = decodeToken(token).user
    // next(req)
}

*app.ts*

...
import {secretMiddleware} from './secret-middleware.ts'
import * as bodyParser from 'body-parser'


@MicroRouter()
class MyApp {

    @MicroMethod.Get('/secret-data', secretMiddleware)
    showSecret(req, res): void {
        res.send('you shall pass')
    }

    // Example with body-parser
    @MicroMethod.Get('/public-data', bodyParser.json())
    showSecret(req, res): void {
        res.send('nothing confidential here')
    }
}


MicroBootstrap(MyApp)

Test it

$ curl -H "Authorization: Bearer myTopSecretToken" http://localhost:3000/secret-data
$ you shall pass
$ curl -H "Authorization: Bear myTopSecretToken" http://localhost:3000/secret-data
$ token_malformed
$ curl http://localhost:3000/secret-data
$ missing_token

Router Scoped Middleware

See MicroRouter

results matching ""

    No results matching ""