DEV Community 👩‍💻👨‍💻

sonicx180
sonicx180

Posted on

How to create an Express JS middleware

Hey there! Today I'm going to show you how to create a express js middleware

Setup > read more on Creating an express server

Okay, now that we have our server, we can add the middleware.
After the constant variable const app = express() and before the

app.get('/', (req,res) => {
res.send("Hello World!")
}


, add this line of code.

app.use((req,res,next) => {
console.log(req.method + " " + req.ip);
next();
})
Enter fullscreen mode Exit fullscreen mode

And that my friends, is a basic middleware function.
Let me break it down for you.

app.use() is an express function for middleware.
Then we create an ES6 arrow function.
We log the method (like the HTTP verbs GET, POST) the user is using into the console and their ip.
The last line of code is the next function. If you don't put that, express will not move on to the next middleware.

A trick you can do with middleware

*Use middlware on a certain route *
app.use('/route',middleware);

Or even

app.get("/route",middleware, (req,res) => {
res.send("I used Middlware!")
}

And that's about it. Read more on middleware at Express Js using Middlware.
Thanks to freecodecamp for example middleware!

Like and Follow if you haven't!

Top comments (0)

Build Anything...


Use any Linode offering to create something for the DEV x Linode Hackathon 2022. A variety of prizes are up for grabs, inculding $1,000 USD. 👀

Join the Hackathon <-