Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 22, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

      July 22, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 22, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Harden Your Node.js APIs – Security Best Practices

    How to Harden Your Node.js APIs – Security Best Practices

    April 25, 2025

    If you’ve built an API with Node.js, chances are you’ve thought about security – at least a little.

    Maybe you’ve heard about SQL injection, brute force attacks, or data leaks.

    But here’s the thing: it’s not just about big hacks. Even small gaps in your API can lead to big problems. And no one wants to get that “your data’s been exposed” message.

    In this article, I’ll walk you through seven ways to harden your Node.js API.

    These are practical tips you can apply right away. I’ll keep the code examples simple and the language even simpler. Let’s get into it.

    1. Use Environment Variables

    Storing sensitive data like database credentials, API keys, or JWT secrets directly in your code is risky. If your code ends up in the wrong hands, so does everything else.

    Instead, store this data in a .env file and use the dotenv package to access it:

    require('dotenv').config();
    
    const dbPassword = process.env.DB_PASSWORD;
    

    Make sure you never commit your .env file. Add it to your .gitignore file to keep it private.

    2. Validate All Input

    Attackers love user input.

    If you don’t check what comes into your API, they’ll sneak in commands, inject code, or crash your app.

    The best way to stop them is by validating every piece of input. Use a package like Joi or zod to define what your API expects:

    const Joi = require('joi');
    
    const schema = Joi.object({
      username: Joi.string().alphanum().min(3).max(30).required(),
      password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{6,30}$')).required()
    });
    const { error } = schema.validate(req.body);
    if (error) {
      return res.status(400).send(error.details[0].message);
    }
    

    In the above code, we have defined the exact data type the schema expects. This way, wrong data gets blocked before it reaches your logic or database.

    3. Rate Limit Your Endpoints

    Bots and brute force attacks work by flooding your server with requests. Once your server reaches it limit, your API will crash.

    Set a limit on how often a user can hit your API using middleware like express-rate-limit Here is an example.

    const rateLimit = require('express-rate-limit');
    
    const limiter = rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100 // limit each IP to 100 requests per windowMs
    });
    app.use('/api/', limiter);
    

    The above code restricts API requests coming from an IP address to 100 per 15 minutes. This is like putting a speed bump in front of a runaway car.

    4. Always Use HTTPS

    HTTP sends data in plain text. That means anyone between your server and the user can read it. HTTPS encrypts everything. It’s not optional anymore.

    If you’re using a platform like Heroku or Vercel, HTTPS is automatic. If you’re self-hosting, you can set it up with services like Let’s Encrypt.

    Also, force HTTPS on all incoming traffic. You can use middleware like this:

    app.use((req, res, next) => {
      if (req.headers['x-forwarded-proto'] !== 'https') {
        return res.redirect('https://' + req.headers.host + req.url);
      }
      next();
    });
    

    Encrypt the ride. Always.

    5. Use Helmet to Secure HTTP Headers

    HTTP headers are key-value pairs sent in requests and responses over the web. They give extra information about what’s being sent – like who’s sending it, what type it is, how it should be handled, and more.

    HTTP headers are small, but they can be powerful tools to protect your app. Helmet is a Node.js middleware that sets secure headers for you.

    const helmet = require('helmet');
    app.use(helmet());
    

    Helmet helps prevent attacks like cross-site scripting (XSS), clickjacking, and others just by setting the right headers.

    One line of code, a big step up in security.

    6. Sanitize Data to Prevent Injection Attacks

    Injection attacks happen when you blindly trust input and plug it into a command or query.

    For example, an attacker might submit a piece of text that turns into a command in your database.

    You should sanitize data before it gets to any sensitive function. Libraries like express-mongo-sanitize or xss-clean help clean up malicious input.

    const mongoSanitize = require('express-mongo-sanitize');
    const xss = require('xss-clean');
    
    app.use(mongoSanitize());
    app.use(xss());
    

    This strips out dangerous characters and scripts that could do real damage.

    7. Use Strong Authentication and Authorisation

    Authentication is about knowing who the user is, and authorisation is about what they can do. You need both, and you need them to be strong.

    Use JWT (JSON Web Tokens) or sessions to manage logged-in users. Here’s a quick JWT example:

    const jwt = require('jsonwebtoken');
    
    const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
      expiresIn: '1h'
    });
    

    Always verify the token before letting a user access protected routes:

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    

    And don’t forget roles. A user who can view data shouldn’t be able to delete it unless they’re supposed to.

    Final Thoughts

    Security isn’t just a feature – it’s a habit. You can’t do everything all at once, but you can start with a few key changes.

    Use environment variables. Validate your inputs. Add rate limiting. Move to HTTPS. Install Helmet. Sanitize everything. Lock down your authentication.

    Each of these steps is a small lock on a big door. The more you add, the harder it is for someone to break in. So take a little time now. Your future self and your users will thank you.

    For more cybersecurity tutorials, join our newsletter. To learn the basics of Offensive Cybersecurity, check out our Security Starter Course.

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHow to Create Models in Your Django Project
    Next Article How to Change Your Django Secret Key (Without Breaking Your App)

    Related Posts

    Development

    GPT-5 is Coming: Revolutionizing Software Testing

    July 22, 2025
    Development

    Win the Accessibility Game: Combining AI with Human Judgment

    July 22, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-37885 – KVM Linux Kernel MSI Route Handling Use-After-Free Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Monitor not paper-y enough? A 25-inch color E Ink monitor just dropped for *checks notes* $1,900

    News & Updates

    This fan-requested Microsoft Teams feature could have prevented a major livestream blunder

    News & Updates

    8 most exciting AI features and tools revealed at Google I/O 2025

    News & Updates

    Highlights

    CVE-2025-3793 – Buddypress WordPress Force Password Change Plugin Authentication Bypass

    April 24, 2025

    CVE ID : CVE-2025-3793

    Published : April 24, 2025, 9:15 a.m. | 1 hour, 28 minutes ago

    Description : The Buddypress Force Password Change plugin for WordPress is vulnerable to authenticated account takeover due to the plugin not properly validating a user’s identity prior to updating their password through the ‘bp_force_password_ajax’ function in all versions up to, and including, 0.1. This makes it possible for authenticated attackers, with subscriber-level access and above and under certain prerequisites, to change arbitrary user’s passwords, including administrators, and leverage that to gain access to their accounts.

    Severity: 4.2 | MEDIUM

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    CVE-2025-26646 – Microsoft .NET Path Traversal Spoofing

    May 13, 2025

    Salt Typhoon Cyberattack: FBI Investigates PRC-linked Breach of US Telecoms

    April 25, 2025

    CVE-2025-20199 – “Cisco IOS XE CLI Privilege Escalation Vulnerability”

    May 7, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.