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!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

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