DEV Community

Cover image for Interesting middlewares in Node.js and Express.js API for security
Luiz Calaça
Luiz Calaça

Posted on

Interesting middlewares in Node.js and Express.js API for security

Hi, Devs!

Look at this piece of code into the main app.js and its middlewares:

const express = require('express');
const app = express();
const cors = require('cors')
const helmet = require("helmet");
const morgan = require("morgan")
const rateLimit = require("express-rate-limit")

const limiter = rateLimit({
    windowMs: 60 * 1000, // 1 minute
    max: 50, // limit each IP to 50 requests per windowMs
    message: "Too many accounts created from this IP, please try again after a minute"
});

app.use(morgan("common")) //just for logs
app.use(helmet());
app.use(cors());
app.use(limiter)
app.use(express.json());
app.get("/", (res, req) => {
    res.status(200).send("Security into a Node.js API")
})
Enter fullscreen mode Exit fullscreen mode

First tip: Use TLS
It's necessary to create a security's and would be the middle between the connection and the data. One is the free TLS certificate from Let’s Encrypt.

☠️ helmet
"Helmet can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately." [Docs]

☠️ cors
"CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options."
[Docs]

☠️ express-rate-limit
"Use to limit repeated requests to public APIs and/or endpoints such as password reset" [Docs]

That's simple and helps a lot! Code it!

Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Top comments (0)