Flask and React are a great pairing: fast to build, flexible, and easy to deploy. But that same speed means security often gets pushed to "later," and later usually means after something breaks.
I work as a secure software engineer, and these five mistakes keep showing up in tutorials, side projects, and early-stage apps. None of them are exotic. All of them are fixable in a few lines.
1. Trusting user input without validation
The mistake: Reading values straight from request.get_json() and using them as if they were safe and correctly shaped.
python
# ❌ Before
@app.route("/register", methods=["POST"])
def register():
data = request.get_json()
email = data["email"] # KeyError if missing, anything if present
password = data["password"] # no length or type checks
create_user(email, password)
return {"message": "ok"}, 201
Missing fields crash the endpoint, and unexpected types or oversized strings flow deeper into your app.
The fix: Validate every request body against a schema before touching it. Pydantic works well for this (pip install pydantic email-validator).
python
# ✅ After
from flask import request, jsonify
from pydantic import BaseModel, EmailStr, Field, ValidationError
class RegisterSchema(BaseModel):
email: EmailStr
password: str = Field(min_length=8, max_length=128)
name: str = Field(min_length=1, max_length=80)
@app.route("/register", methods=["POST"])
def register():
try:
payload = RegisterSchema(**(request.get_json(silent=True) or {}))
except ValidationError as e:
return jsonify({"errors": e.errors()}), 400
create_user(payload.email, payload.password, payload.name)
return {"message": "ok"}, 201
Frontend validation in React is good for user experience, but it is not security. Anyone can send requests to your API without your UI. Always validate on the server.
2. Storing JWTs in localStorage
The mistake: Saving the access token where any JavaScript on the page can read it.
javascript
// ❌ Before
const { data } = await axios.post("/api/login", credentials);
localStorage.setItem("token", data.token);
axios.defaults.headers.common["Authorization"] = `Bearer ${data.token}`;
If an attacker lands a single XSS payload (a vulnerable dependency, an unsanitized dangerouslySetInnerHTML), they can read localStorage and steal the session.
The fix: Keep the token in an HttpOnly, Secure, SameSite cookie so JavaScript cannot read it. With flask-jwt-extended:
python
# ✅ After (Flask)
from flask import jsonify
from flask_jwt_extended import (
JWTManager, create_access_token, set_access_cookies
)
app.config["JWT_TOKEN_LOCATION"] = ["cookies"]
app.config["JWT_COOKIE_SECURE"] = True # HTTPS only
app.config["JWT_COOKIE_SAMESITE"] = "Lax"
app.config["JWT_COOKIE_CSRF_PROTECT"] = True # keep this on with cookies
jwt = JWTManager(app)
@app.route("/login", methods=["POST"])
def login():
# ...verify credentials...
token = create_access_token(identity=str(user.id))
resp = jsonify({"message": "logged in"})
set_access_cookies(resp, token)
return resp
javascript
// ✅ After (React)
// Send cookies with every request. The token itself never touches JS.
axios.defaults.withCredentials = true;
Trade-off to know: cookies are automatically attached by the browser, which opens the door to CSRF. That's why JWT_COOKIE_CSRF_PROTECT stays on, and your React app sends the CSRF token (from the csrf_access_token cookie) in an X-CSRF-TOKEN header on state-changing requests.
3. A wide-open CORS configuration
The mistake: Making CORS errors disappear during development with CORS(app) and never tightening it.
python
# ❌ Before
from flask_cors import CORS
CORS(app) # allows requests from any origin
Combined with cookie-based auth, an over-permissive policy lets other websites make requests to your API from a visitor's browser.
The fix: Allow only the origins you actually use, and be explicit about credentials.
python
# ✅ After
import os
from flask_cors import CORS
ALLOWED_ORIGINS = os.environ.get(
"ALLOWED_ORIGINS", "http://localhost:5173"
).split(",")
CORS(
app,
origins=ALLOWED_ORIGINS,
supports_credentials=True,
methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Content-Type", "X-CSRF-TOKEN"],
)
Set ALLOWED_ORIGINS to your real production domain in your deployment environment, and never use * together with credentials.
4. Building SQL queries with string formatting
The mistake: Putting user input directly into a SQL string.
python
# ❌ Before
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")
If email is ' OR '1'='1, the query returns every user. With worse payloads, attackers can modify or delete data. SQL injection is decades old and still one of the most damaging bugs around.
The fix: Use parameterized queries so the database treats input as data, never as SQL.
python
# ✅ After (psycopg2 with PostgreSQL)
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
python
# ✅ After (SQLAlchemy ORM)
user = User.query.filter_by(email=email).first()
# ✅ After (SQLAlchemy raw SQL, still safe with bound parameters)
from sqlalchemy import text
db.session.execute(
text("SELECT * FROM users WHERE email = :email"),
{"email": email},
)
The rule is simple: if user input is ever concatenated or f-string-ed into a query, stop and parameterize it.
5. Leaking secrets through .env files and frontend bundles
The mistake: Hardcoding secrets, committing .env to Git, or putting secrets in frontend environment variables.
python
# ❌ Before
app.config["SECRET_KEY"] = "supersecret123"
app.config["DATABASE_URL"] = "postgresql://admin:MyPassword@db.example.com/app"
bash
# ❌ Before: committed to the repo, and exposed to the browser
REACT_APP_STRIPE_SECRET_KEY=sk_live_...
Two things go wrong here. Anything committed to Git can live in history forever, even after you delete the file. And any variable prefixed with REACT_APP_ (or VITE_ in Vite) is bundled into your frontend code, so every visitor can read it.
The fix:
python
# ✅ After (Flask)
import os
from dotenv import load_dotenv
load_dotenv() # reads .env locally; in production use real environment variables
app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]
app.config["DATABASE_URL"] = os.environ["DATABASE_URL"]
bash
# ✅ .gitignore
.env
.env.*
!.env.example
Commit a .env.example with placeholder values so teammates know what to set.
Keep secrets on the backend only. Frontend variables should hold public values, such as an API base URL.
If a secret was ever committed, rotate it. Deleting the file is not enough.
Add a scanner like gitleaks as a pre-commit hook or CI step to catch leaks early.
Top comments (0)