Description
POST requests to the /api/auth/register endpoint return 500 Internal Server Error during registration. Server starts up fine and connects to MongoDB, but the register route fails at runtime. The error is not currently showing a full traceback in the response — we need the root cause (duplicate key, hashing error, JWT misconfiguration, etc.).
Reproduction Steps
- Start the backend:
(venv) C:\Users\kaust\OneDrive\Documents\GitHub\Singularity\backend> py run.py
- Send a registration request:
curl -v -X POST http://127.0.0.1:8000/api/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"Pass1234"}'
Observed Behavior
- The server prints startup logs and connects to MongoDB, then:
INFO: 127.0.0.1:62275 - "OPTIONS /api/auth/register HTTP/1.1" 200 OK
Registration error:
INFO: 127.0.0.1:62275 - "POST /api/auth/register HTTP/1.1" 500 Internal Server Error
- The client receives HTTP 500; no detailed traceback is currently visible in logs posted here.
Expected Behavior
- Successful registration returns
201 or 200 with created user id / token.
- If the request is invalid (e.g., duplicate email), return
400 with a helpful error message (e.g., "Email already registered").
- Full traceback logged to server console (in dev) for easier debugging.
Environment
- OS: Windows (logs from
C:\Users\kaust\OneDrive\...)
- Python: running
py run.py from venv
- Server: Uvicorn (auto reload)
- Database: MongoDB (connected; DB name:
singularity)
- Stack: FastAPI + Mongo driver (Motor )
Logs
(venv) C:\Users\kaust\OneDrive\Documents\GitHub\Singularity\backend>py run.py
INFO: Will watch for changes in these directories: ['C:\\Users\\kaust\\OneDrive\\Documents\\GitHub\\Singularity\\backend']
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Started reloader process [31464] using StatReload
INFO: Started server process [22052]
INFO: Waiting for application startup.
✅ Connected to MongoDB: singularity
📊 Database indexes created
INFO: Application startup complete.
INFO: 127.0.0.1:62275 - "OPTIONS /api/auth/register HTTP/1.1" 200 OK
Registration error:
INFO: 127.0.0.1:62275 - "POST /api/auth/register HTTP/1.1" 500 Internal Server Error
Possible Root Causes (prioritized)
- Duplicate key error on insert (unique index on
email) → should be handled and returned as 400.
- Missing / incorrectly loaded environment variables (e.g.,
JWT_SECRET) causing JWT encoding to fail.
- Password hashing error (wrong type passed to
bcrypt/passlib).
- BSON /
ObjectId conversion errors when creating/reading IDs.
- Unhandled exceptions from DB driver (Motor / PyMongo network or schema errors).
- Any other unhandled runtime exception in the register handler.
Suggested Immediate Debugging Steps
-
Enable detailed exceptions in dev
Set FastAPI debug for local debugging:
app = FastAPI(debug=True)
-
Enable uvicorn debug logging when launching:
uvicorn run:app --reload --log-level debug
(Or ensure py run.py passes log_level="debug" to uvicorn.run.)
-
Add exception logging to the register route to capture full traceback:
import logging, traceback
logger = logging.getLogger("uvicorn.error")
try:
# handler logic...
except Exception:
logger.exception("Unhandled exception during registration")
traceback.print_exc()
raise HTTPException(status_code=500, detail="Internal Server Error")
-
Test with a unique email to rule out DuplicateKeyError. If failure only occurs for certain emails, inspect the unique index:
- Run
db.users.getIndexes() in Mongo shell or check via MongoDB Compass.
-
Verify environment variables like JWT_SECRET are set and not None. Add an early runtime check:
import os
if not os.environ.get("JWT_SECRET"):
raise RuntimeError("JWT_SECRET not set")
Quick Fix Examples (to handle common errors)
from pymongo.errors import DuplicateKeyError
try:
await db.users.insert_one(user_doc)
except DuplicateKeyError:
raise HTTPException(status_code=400, detail="Email already registered")
- Ensure password hashing receives bytes and returns a string:
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
user_doc['password'] = hashed.decode('utf-8')
- Validate
jwt.encode uses a valid secret:
import os
SECRET_KEY = os.environ.get('JWT_SECRET')
if not SECRET_KEY:
raise RuntimeError("JWT_SECRET not set")
token = jwt.encode({"user_id": user_id}, SECRET_KEY, algorithm="HS256")
Acceptance Criteria (for closing this issue)
- The register endpoint returns
200/201 for valid new registrations.
- Duplicate registration returns
400 with a descriptive message.
- Any server exceptions are logged with full traceback during development.
- Add a unit/integration test covering registration success and duplicate-email case.
Description
POST requests to the
/api/auth/registerendpoint return500 Internal Server Errorduring registration. Server starts up fine and connects to MongoDB, but the register route fails at runtime. The error is not currently showing a full traceback in the response — we need the root cause (duplicate key, hashing error, JWT misconfiguration, etc.).Reproduction Steps
Observed Behavior
Expected Behavior
201or200with created user id / token.400with a helpful error message (e.g., "Email already registered").Environment
C:\Users\kaust\OneDrive\...)py run.pyfrom venvsingularity)Logs
Possible Root Causes (prioritized)
email) → should be handled and returned as 400.JWT_SECRET) causing JWT encoding to fail.bcrypt/passlib).ObjectIdconversion errors when creating/reading IDs.Suggested Immediate Debugging Steps
Enable detailed exceptions in dev
Set FastAPI debug for local debugging:
Enable uvicorn debug logging when launching:
(Or ensure
py run.pypasseslog_level="debug"touvicorn.run.)Add exception logging to the register route to capture full traceback:
Test with a unique email to rule out
DuplicateKeyError. If failure only occurs for certain emails, inspect the unique index:db.users.getIndexes()in Mongo shell or check via MongoDB Compass.Verify environment variables like
JWT_SECRETare set and notNone. Add an early runtime check:Quick Fix Examples (to handle common errors)
jwt.encodeuses a valid secret:Acceptance Criteria (for closing this issue)
200/201for valid new registrations.400with a descriptive message.