Documentation
Middlewares

Middlewares

A middleware is a function that operates between an incoming request and the corresponding outgoing response. It serves as a processing layer before or after an endpoint handler, carrying out tasks like logging, authentication, and other sorts of data manipulation.

Middlewares in zhttp are essentially just express middlewares, with two extra properties: their type (indicating when to run them), and an optional name. Middlewares can be bound on multiple levels:

  • The server
  • A controller
  • An endpoint

Basic middleware example

// ../../../../examples/concept-middleware.ts
 
import { type Request, type Response, type NextFunction } from 'express'
import { middleware, MiddlewareTypes } from '@zhttp/core'
 
export const lastVisitMiddleware = middleware({
  name: 'lastVisitMiddleware',
  type: MiddlewareTypes.BEFORE,
  handler (req: Request, res: Response, next: NextFunction) {
    const now = new Date()
    const lastVisitCookieValue = req.cookies.beenHereBefore
    const lastVisitTime = lastVisitCookieValue != null ? new Date(String(lastVisitCookieValue)) : undefined
    res.cookie('beenHereBefore', now.toISOString())
    if (lastVisitTime == null) {
      console.log('Seems like we\'ve got a new user 👀')
      next(); return
    }
    const daysSinceLastVisit = (now.getTime() - lastVisitTime.getTime()) / (1000 * 60 * 60 * 24)
    console.log(`It's been ${daysSinceLastVisit} days since this user last visited.`)
    next()
  }
})