DEV Community

shema-surge
shema-surge

Posted on

2 1

Writing custom middleware functions in NodeJS

Middleware is any code that runs on the server between getting a request and a response. Middleware functions in NodeJS have access to the request object, the response object and the next function.

function middleFunc(req,res,next){
    req.message:'Hello'
    next()
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the function middleFunc is a middleware function that takes three parameters: req,res,and next. The function sets a req.message to 'Hello'.

Middleware functions do not end the request-response cycle but they have to call next() to either pass execution to the next middleware function or the request handler itself. If next() function is not called, the request will hang.

A middleware function can be run by passing it between the path and callback function of the request handler.

app.get('/',middleFunc,(req,res)=>{
    res.json(req.message)
})
Enter fullscreen mode Exit fullscreen mode

Here, middleFunc will run first then when next() is called, the execution is passed to the request handler which prints the message.

It is also possible to rewrite the middleware function as an Application-level middleware like this,

app.use((req,res,next)=>{
    req.message = 'Hello'
    next()
})
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay