In web development term, a middleware is a function in which the third parameter “next” is a special function used to pass the HTTP request to the next middleware in the HTTP request chain. 

 

“Middleware can perform any operation, make changes to the request and response objects, and end the request. If it does not end the cycle then it must call next( ) to pass control to the next middleware function otherwise the request will be left hanging!” wrote Craig Morten.

 

When used, the middleware receives three arguments for request, response, and next parameters respectively. We can use any function as a middleware as long as this function has three parameters and it calls the next( ) function to pass the HTTP request and response to the next middleware. To use any middleware, we must pass it as an argument to the use method of the application object.

 

// main.ts

import opine from "https://deno.land/x/opine@2.2.0/mod.ts"

const app = opine()

import indexRouter from './routes/index.ts'
app.use('/',indexRouter)

app.listen(3000)
console.log("Opine started on port 3000")

 

// routes/index.ts

import {Router} from "https://deno.land/x/opine@2.2.0/mod.ts"
const indexRouter = Router()

const getDate = (req,res,next)=>{
    const date = (new Date()).toLocaleDateString('it-IT')
    req.date = date
    next()
}

indexRouter.use(getDate)

indexRouter.get('/', (req,res)=>{
    res.send(`Today is ${req.date}`)
})

indexRouter.get('/post/:id', (req,res)=>{
    res.send(`The id of the post is ${req.params.id}`)
})

export default indexRouter