<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Govind Tiwari</title>
    <description>The latest articles on Forem by Govind Tiwari (@govind_tiwari).</description>
    <link>https://forem.com/govind_tiwari</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2160210%2F72d30e7e-13da-4d16-89ef-a3411dbe0407.jpg</url>
      <title>Forem: Govind Tiwari</title>
      <link>https://forem.com/govind_tiwari</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/govind_tiwari"/>
    <language>en</language>
    <item>
      <title>Best Security Practices in Express.js – A Beginner's Guide</title>
      <dc:creator>Govind Tiwari</dc:creator>
      <pubDate>Mon, 28 Apr 2025 12:20:18 +0000</pubDate>
      <link>https://forem.com/govind_tiwari/best-security-practices-in-expressjs-a-beginners-guide-19k1</link>
      <guid>https://forem.com/govind_tiwari/best-security-practices-in-expressjs-a-beginners-guide-19k1</guid>
      <description>&lt;p&gt;Hi there! 👋&lt;/p&gt;

&lt;p&gt;Welcome to my very first blog post! I'm a developer with about six months of hands-on experience in building web applications, and through this journey, I’ve realized how crucial security is—especially when working with Express.js (fast, unopinionated, minimalist web framework for Node.js), one of the most popular Node.js frameworks.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft64u5ylujanu9bou035c.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft64u5ylujanu9bou035c.gif" alt="Sad Cat" width="128" height="128"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this post, I’ll share some of the best security practices I’ve learned (sometimes the hard way!) while working with Express.js. Whether you're just starting out or looking to reinforce your backend with better security habits, I hope this guide helps you build safer and more reliable apps.&lt;/p&gt;

&lt;p&gt;Let’s get started!&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Use Helmet
&lt;/h2&gt;

&lt;p&gt;Helmet is a middleware for Express that improves your app's security by automatically setting helpful HTTP headers. While it's not a complete security solution, it adds a protective layer against several common web threats by configuring headers like X-Content-Type-Options, X-DNS-Prefetch-Control, and more.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const helmet = require('helmet');
const app = require('express')();

app.use(helmet());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Implement Rate Limiting
&lt;/h2&gt;

&lt;p&gt;Rate limiting is an effective way to reduce the risk of brute-force attacks by restricting how many requests a user can make over a specific period. In Express.js applications, this can be implemented using the express-rate-limit middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100,
});

app.use(limiter);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Keep Dependencies Updated
&lt;/h2&gt;

&lt;p&gt;Software vulnerabilities are found frequently, and relying on outdated packages can put your application at risk. To help keep your dependencies secure, make use of tools such as npm audit or Snyk to detect and resolve known security issues.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm audit fix
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Sanitize Input
&lt;/h2&gt;

&lt;p&gt;Sanitizing input is a key defense against injection attacks. Always assume user input may be harmful—validate and clean it thoroughly before using it in your application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const app = express();
const { body, validationResult } = require('express-validator');

app.post('/user',
  body('username').isAlphanumeric(),
  body('email').isEmail(),
  (req, res) =&amp;gt; {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    // Proceed with handling request
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Use HTTPS
&lt;/h2&gt;

&lt;p&gt;Data sent over HTTP isn’t protected, which leaves it open to being intercepted or modified. To secure communication, switch to HTTPS. In Express.js, this can be achieved by integrating Node’s https module with fs to load your SSL/TLS certificates.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const https = require('https');
const fs = require('fs');
const app = require('express')();

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, app).listen(443);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Handle Errors Properly
&lt;/h2&gt;

&lt;p&gt;While Express.js provides built-in error handling, it's a best practice to create custom error handling middleware. This allows for better control over how errors are caught and managed in your application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use((err, req, res, next) =&amp;gt; {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  7. Use Cookies Securely
&lt;/h2&gt;

&lt;p&gt;When using cookies for session management, it's essential to set the secure and httpOnly flags. The secure flag ensures cookies are only sent over HTTPS, while httpOnly prevents client-side scripts from accessing the cookie, safeguarding against potential security threats like XSS.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const session = require('express-session');

app.use(session({
  secret: 'your-secret',
  cookie: {
    secure: true,
    httpOnly: true,
  },
  // other configuration
}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  8. Avoid Revealing Stack Traces
&lt;/h2&gt;

&lt;p&gt;In Express.js, stack traces are exposed to the client by default when an error occurs. To prevent revealing sensitive information, always disable stack traces in production environments by using custom error handling middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (app.get('env') === 'production') {
  app.use((err, req, res, next) =&amp;gt; {
    res.status(500).send('Server Error');
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  9. Secure File Uploads
&lt;/h2&gt;

&lt;p&gt;When handling file uploads, it's crucial to verify the file type, set size limits, and scan for malware to protect your application from potential threats.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multer = require('multer');
const upload = multer({
  dest: 'uploads/',
  limits: { fileSize: 1000000 },
  fileFilter: (req, file, callback) =&amp;gt; {
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
      return callback(new Error('Only image files are allowed!'), false);
    }
    callback(null, true);
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  10. Authenticate &amp;amp; Authorize
&lt;/h2&gt;

&lt;p&gt;Implementing robust authentication and authorization checks is essential for security. Tools like Passport.js can simplify and strengthen the management of user authentication in your application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy((username, password, done) =&amp;gt; {
  // Implement your verification logic
}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By following these best practices, you're not only securing your application but also protecting your users' data and trust. Keep in mind, security is an ongoing process that requires regular code reviews, monitoring, and updates to stay ahead of potential threats. 😉&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkhfot92uq6y2s554em9e.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkhfot92uq6y2s554em9e.gif" alt="Happy &amp;amp; Dancing Cat" width="200" height="200"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>hacking</category>
      <category>express</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
