The uMiddleware decorator allows you to wrap a handler inside a middleware. If you need a router-wider middleware, use the middleware parameter in uRouter. You may use existing express.js 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.



const secretMiddleware = (req: uRequest, res: uResponse, next: NextFunction) => {

    const secret = req.headers['authorization']

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

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

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

    // imaginary validation
    const tokenValid = true

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


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


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

import {
} from 'microdose'

class MyApp {

  showSecret(req: uRequest, res: uResponse): void {
    res.send('you shall pass')

  // Example with body-parser
  showSecret(req: uRequest, res: uResponse): void {
    res.send('nothing confidential here')

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 uRouter

results matching ""

    No results matching ""