Middleware & Project structure.

mahich123

Mahich123

Posted on December 22, 2022

Middleware & Project structure.

Middleware:
Middleware is a handler or we can say controller function . We sent request to server and server gives a response. Middleware are thoose functions which appears in the middle of request and response bellow shown the structure of a middleware :

middleware

The middleware function looks like ,

(req, res, next) => {
  ....
} 
Enter fullscreen mode Exit fullscreen mode

It has access to request and response object also it has next function . When client sents request to server that server sents that request to middleware then middleware gives back that response to client . Middleware runs it functionality to give response. We can write custom middlewares :

const myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}
Enter fullscreen mode Exit fullscreen mode

created a middleware called myLogger which just prints LOGGED . We can see there's a next function it basically passes myLogger response to next middleware . In a server it can has multiple middlewares or could be have single . So now we know what is middleware but why we use it.

Why to use middleware:
Middleware are used to add logging and authentication functionality. If we want to record the number request we get we can use middleware.

Project Structure:
When we create projects most of the time we don't look at the structure of project. We just create the project but after some day when we get back to that same projects we may ran into bugs and any other errors at that time it becomes difficult to solve that issue because our project remains unorganized . If we organize our project it becomes easier to get to know that files . Sharing a project structure which feels organized for me you may keep your files in your own way ,

app
config
controller
db
error
lgos
middleware
routes
test
util

.env
.gitignore
server.js

for particular work created separated directory which helps to know the workflow and it becomes easier to debug error.

That's all for today . Thank you for reading !!

πŸ’– πŸ’ͺ πŸ™… 🚩
mahich123
Mahich123

Posted on December 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related