5 Security Mistakes I See in Flask + React Apps (and How to Fix Them)
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.…
Flask and React are a popular combination for building web applications, offering speed, flexibility, and ease of deployment. However, the rapid development process can lead to overlooking security measures, which can have serious consequences if exploited. As a secure software engineer, I have observed five common mistakes that frequently appear in Flask+React applications. These issues are not complex and can be easily addressed with a few lines of code.
1. Ignoring user input validation: The error occurs when developers directly read values from the `request.get_json()` method and treat them as safe and properly formatted. This approach can result in `KeyError` exceptions if fields are missing or in cases where unexpected data types or oversized strings are passed to other parts of the application.
To prevent this, it is crucial to validate every request body against a defined schema before processing it. Pydantic is a recommended library for schema validation (install it using `pip install pydantic email-validator`).
2. Storing JSON Web Tokens (JWTs) in localStorage: Saving the access token in `localStorage` exposes it to potential attacks, as any JavaScript running on the page can read this data. An XSS vulnerability, which can be introduced by an unsanitized dependency or a maliciously crafted piece of HTML, could allow an attacker to steal the session.
To mitigate this risk, store the JWT in an `HttpOnly`, `Secure`, `SameSite` cookie. This ensures that JavaScript cannot access the token. With the Flask extension `flask-jwt-extended`, you can configure the application to use cookies for token storage:
```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
```
On the React frontend, ensure that every request includes the token in the `Authorization` header using a cookie, rather than storing it in `localStorage`.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.