‹ Back to Home

SQL injection, XSS and CSRF start in code you already wrote

Friday evening concatenations still cause Monday incidents. Here is how SQL injection, XSS, CSRF, leaked .env files and dusty dependencies get fixed in code you would actually merge.

Keerthika 7 min read
Follow on Google
Web Dev SQL injection, XSS and CSRF start in code you already wrote 7 min left Follow on Google

TamilTech AI summary

  • Parameterised queries, not string-built SQL
  • textContent over innerHTML for untrusted data
  • CSRF tokens plus SameSite for money-moving POSTs

AI-assisted summary, checked by the TamilTech editorial team.

0:00
0:00
🔒 Listen is for subscribers. Subscribe

Treat every input as data, never as instructions: that single rule is how you stop SQL injection, XSS and CSRF in the code you already wrote. This article walks Tamil Nadu developers through five production habits — parameterised queries, rendering untrusted strings as text, CSRF tokens with SameSite cookies, secrets kept in the environment not Git, and pinned dependencies — so a Friday ticket on OMR does not become tomorrow's incident.

  • Never build SQL by concatenating user input. Use parameterised queries.
  • Render untrusted data as text, not HTML.
  • Protect state-changing requests with CSRF tokens and SameSite cookies.
  • Keep secrets in .env and the host environment, never in Git.
  • Audit and pin dependencies so yesterday's package is not tomorrow's incident.

What is web security for developers, in one line?

Friday, 7.40 pm, OMR. Someone pastes a user email into a SQL string because standup is in twenty minutes. That line is still how a lot of production mess starts. Not a cinema hacker. A ticket. A plus sign.

Web security for working developers is one rule: treat every input as data, never as instructions. The browser, the database, and Git should see only what they must. XSS, CSRF and SQL injection are names for mixing user text into HTML, cross-site POSTs, and SQL.

You do not need a red-team budget. You need the boring defaults below.

How do you stop SQL injection with parameterised queries?

SQL injection happens when user text becomes part of the SQL grammar. The database then runs the attacker's sentence, not yours.

Glue a login email into quotes, and one extra quote can change the whole statement. You leak rows. Sometimes you leak the users table. Login boxes, IRCTC-style PNR lookups, and search-by-mobile fields are favourite doors because the data is tickets and personal records.

The fix is a parameterised query. Placeholders in the SQL. Values sent separately. The driver keeps the email from being parsed as code.

import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

export async function findUserByEmail(email) {
  const { rows } = await pool.query(
    'SELECT id, email FROM users WHERE email = $1',
    [email]
  );
  return rows[0] ?? null;
}

The idea is the same in Node, Python, Java and PHP. Drivers like pg and mysql2, JDBC PreparedStatement, Django's ORM — they exist so you stop building SQL with plus signs. Raw SQL is fine. String-built SQL is not.

A category filter on a Flipkart-like catalogue follows the same rule. The id goes in as a bound parameter, not as a chunk you interpolated because the ticket was on fire.

How do you kill XSS with escaping, not hope?

XSS is cross-site scripting. Attacker-controlled text is later treated by the browser as HTML or JavaScript. The next person who opens that comment or profile name runs someone else's script on your origin. Session cookies and admin screens sit one tab away.

In production this is almost always innerHTML, a leftover jQuery html call, or a template that forgot to escape. You wanted a display name. You rendered a payload.

Put untrusted strings into the DOM as text.

const nameEl = document.querySelector('#user-name');
nameEl.textContent = user.name;

// Do not do this with untrusted data:
// nameEl.innerHTML = user.name;

React, Vue and Svelte already escape by default. The hole opens when you reach for dangerouslySetInnerHTML, v-html, or a rich-text editor with a homemade sanitiser. Markdown preview is a repeat offender. Use a maintained library, and still default to text.

A Content-Security-Policy that bans inline scripts is a seatbelt. It does not make innerHTML with a user name acceptable.

Why do CSRF tokens still matter on a UPI-style form?

CSRF is cross-site request forgery. The user is logged into your site. Another origin tricks the browser into firing a POST — change the email, add a payee, send ₹2,000. The session cookie goes along. Your server sees a cookie and trusts it.

SameSite=Lax blocks many cross-site POSTs. Keep it. Do not stop there for money movement. For every state-changing request, put a CSRF token in the form or a custom header, and check it on the server. A third-party page cannot read that token.

<form method="POST" action="/transfer">
  <input type="hidden" name="_csrf" value="TOKEN_FROM_SERVER">
  <input name="to_upi" value="user@okaxis">
  <input name="amount" value="500">
  <button type="submit">Pay</button>
</form>

// Server: compare body token with the session token.
if (req.body._csrf !== req.session.csrfToken) {
  return res.status(403).send('CSRF check failed');
}

Reject mismatches with 403. Check the Origin header as a second belt. GET must not move money. SameSite=Strict on the session cookie when the product can live with it.

Where should secrets and .env files live?

If a secret is in the repo, treat it as public. .env is for your laptop. Production reads variables from the host secret store. Git may hold .env.example with names and blank values. Never the values.

.env — laptop only, never commit
DATABASE_URL=postgres://app:[email protected]:5432/shop
UPI_WEBHOOK_SECRET=replace-me

# .env.example — this one can go to Git
DATABASE_URL=
UPI_WEBHOOK_SECRET=

Rotate anything that sat in a screenshot, a WhatsApp dump, or a college GitHub. Do not ship API keys in the frontend bundle. If the browser can see it, the user can see it. Interviewers will fail a hardcoded cloud key in config.js. They should.

How do you catch dependency holes before they ship?

Half the app is other people's packages. One abandoned middleware is enough.

Commit a lockfile. Run npm audit or pip-audit in CI. Turn on Dependabot or GitLab dependency alerts so bumps arrive as pull requests, not as a Sunday incident.

Do not drop a random package into a payments service because a blog said it was handy. Pin versions. When audit says critical, read the advisory and bump.

Which mistakes get people into trouble?

We keep making the same ones.

  • Building SQL with template strings "only for this admin report".
  • Rendering a user name with innerHTML because styling was hard.
  • A CSRF token on login, none on the transfer endpoint.
  • Committing .env, then deleting it later — Git history still has it.
  • Switching off npm audit because CI went red.
  • Validating only in the browser.
  • Storing a JWT in localStorage and calling it done; one XSS and the token walks out.

The browser is for UX checks. The server is the security boundary. If the API trusts the Angular form, the API is wrong.

Where does this show up in Indian companies and interviews?

Walk into a service-company interview in Chennai, Bengaluru or Hyderabad and you still get asked what SQL injection is, and how XSS differs from CSRF. Product teams at commerce and payments companies will hand you a pull request and wait to see if you flinch at a concatenated query. Campus tests love the OWASP names. What they hire for is whether you reach for bound parameters and textContent without being asked.

On the job the same holes hide in internal admin panels, the ones nobody tests because only employees use it. Employees have browsers. Browsers get tricked.

What should you do now?

Take a tiny Express or Django app with a login, a comment box, and a transfer button. On a local branch only, leave four holes: concatenated SQL, innerHTML for comments, a POST with no CSRF check, a secret in source. Close each hole with the patterns above. Do not put that branch on the public internet.

When those four are gone, open a teammate's PR and look for the same four. That is the work.

Frequently asked questions

5

What is the difference between XSS and CSRF?

XSS tricks the user's browser into running attacker script on your origin. CSRF tricks that same logged-in browser into sending a request the user did not mean. XSS steals the session. CSRF uses the session.

Are parameterised queries enough against SQL injection?

They stop injection in that statement, which is the bug you actually ship. You still want a least-privilege database user, and you still should not build table or column names from raw input.

Does SameSite=Lax replace CSRF tokens?

No. SameSite=Lax blocks a lot of cross-site POSTs and you should set it. Tokens still matter for money movement, older clients, and any flow where SameSite is not enough.

Is npm audit enough for dependency security?

It catches known advisories in your tree. It does not catch bugs you wrote, or a hole so new it has no CVE yet. Keep a lockfile, run audit in CI, and read critical advisories before you ignore them.

Should session tokens live in localStorage?

Prefer httpOnly cookies. localStorage is readable by any script on the page, so one XSS becomes a full account take.

Get tomorrow’s tech news on WhatsApp

One short update a day, free. Follow the TamilTech channel.

What do you think?

people reacted

Keerthika

TamilTech editorial team · 3,891 articles

Keerthika is an editor at TamilTech, the Tamil and English technology publication founded by Praveen Kumar S. She covers AI, smartphones, gadgets, EVs, startups and cybersecurity i...

More from Keerthika

Ask TamilTech on WhatsApp

Tech doubt? Ask in Tamil or English — our WhatsApp assistant answers from TamilTech articles in seconds.

Related stories

Comments (0)

| Supports **bold**, *italic*, `code`

Be the first to comment!

Next story Sessions vs JWT vs OAuth - what should your app use?
TamilTech

TamilTech

Install app for faster access

Earn XP 🏆
WhatsApp
Notifications