<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ injection attacks - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ injection attacks - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 22:25:45 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/injection-attacks/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Harden Your Node.js APIs – Security Best Practices ]]>
                </title>
                <description>
                    <![CDATA[ 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 yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-harden-your-nodejs-apis-security-best-practices/</link>
                <guid isPermaLink="false">680bb2b3917896a550779bcb</guid>
                
                    <category>
                        <![CDATA[ hacking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ https ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ethicalhacking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ injection attacks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Fri, 25 Apr 2025 16:05:07 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745597082780/c803850d-f482-4fcc-a744-4de8fd8a02d8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you’ve built an API with Node.js, chances are you’ve thought about security – at least a little.</p>
<p>Maybe you’ve heard about SQL injection, brute force attacks, or data leaks.</p>
<p>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.</p>
<p>In this article, I’ll walk you through seven ways to harden your Node.js API.</p>
<p>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.</p>
<h2 id="heading-1-use-environment-variables"><strong>1. Use Environment Variables</strong></h2>
<p>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.</p>
<p>Instead, store this data in a <code>.env</code> file and use the <code>dotenv</code> package to access it:</p>
<pre><code class="lang-plaintext">require('dotenv').config();
</code></pre>
<pre><code class="lang-plaintext">const dbPassword = process.env.DB_PASSWORD;
</code></pre>
<p>Make sure you <strong>never</strong> commit your <code>.env</code> file. Add it to your <code>.gitignore</code> file to keep it private.</p>
<h2 id="heading-2-validate-all-input"><strong>2. Validate All Input</strong></h2>
<p>Attackers love user input.</p>
<p>If you don’t check what comes into your API, they’ll sneak in commands, inject code, or crash your app.</p>
<p>The best way to stop them is by validating every piece of input. Use a package like <code>Joi</code> or <code>zod</code> to define what your API expects:</p>
<pre><code class="lang-plaintext">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);
}
</code></pre>
<p>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.</p>
<h2 id="heading-3-rate-limit-your-endpoints"><strong>3. Rate Limit Your Endpoints</strong></h2>
<p>Bots and brute force attacks work by flooding your server with requests. Once your server reaches it limit, your API will crash.</p>
<p>Set a limit on how often a user can hit your API using middleware like <code>express-rate-limit</code> Here is an example.</p>
<pre><code class="lang-plaintext">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);
</code></pre>
<p>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.</p>
<h2 id="heading-4-always-use-https"><strong>4. Always Use HTTPS</strong></h2>
<p>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.</p>
<p>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.</p>
<p>Also, force HTTPS on all incoming traffic. You can use middleware like this:</p>
<pre><code class="lang-plaintext">app.use((req, res, next) =&gt; {
  if (req.headers['x-forwarded-proto'] !== 'https') {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
});
</code></pre>
<p>Encrypt the ride. Always.</p>
<h2 id="heading-5-use-helmet-to-secure-http-headers"><strong>5. Use Helmet to Secure HTTP Headers</strong></h2>
<p>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.</p>
<p>HTTP headers are small, but they can be powerful tools to protect your app. <code>Helmet</code> is a Node.js middleware that sets secure headers for you.</p>
<pre><code class="lang-plaintext">const helmet = require('helmet');
app.use(helmet());
</code></pre>
<p>Helmet helps prevent attacks like cross-site scripting (XSS), clickjacking, and others just by setting the right headers.</p>
<p>One line of code, a big step up in security.</p>
<h2 id="heading-6-sanitize-data-to-prevent-injection-attacks"><strong>6. Sanitize Data to Prevent Injection Attacks</strong></h2>
<p>Injection attacks happen when you blindly trust input and plug it into a command or query.</p>
<p>For example, an attacker might submit a piece of text that turns into a command in your database.</p>
<p>You should sanitize data before it gets to any sensitive function. Libraries like <code>express-mongo-sanitize</code> or <code>xss-clean</code> help clean up malicious input.</p>
<pre><code class="lang-plaintext">const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');

app.use(mongoSanitize());
app.use(xss());
</code></pre>
<p>This strips out dangerous characters and scripts that could do real damage.</p>
<h2 id="heading-7-use-strong-authentication-and-authorisation"><strong>7. Use Strong Authentication and Authorisation</strong></h2>
<p>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.</p>
<p>Use JWT (JSON Web Tokens) or sessions to manage logged-in users. Here’s a quick JWT example:</p>
<pre><code class="lang-plaintext">const jwt = require('jsonwebtoken');

const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
  expiresIn: '1h'
});
</code></pre>
<p>Always verify the token before letting a user access protected routes:</p>
<pre><code class="lang-plaintext">const decoded = jwt.verify(token, process.env.JWT_SECRET);
</code></pre>
<p>And don’t forget roles. A user who can view data shouldn’t be able to delete it unless they’re supposed to.</p>
<h2 id="heading-final-thoughts"><strong>Final Thoughts</strong></h2>
<p>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.</p>
<p>Use environment variables. Validate your inputs. Add rate limiting. Move to HTTPS. Install Helmet. Sanitize everything. Lock down your authentication.</p>
<p>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.</p>
<p><em>For more cybersecurity tutorials,</em> <a target="_blank" href="https://newsletter.stealthsecurity.sh/"><strong><em>join our newsletter</em></strong></a><em>. To learn the basics of Offensive Cybersecurity, check out our</em> <a target="_blank" href="https://start.stealthsecurity.sh/"><strong><em>Security Starter Course</em></strong></a><em>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
