Skip to content

500 Internal Server Error when POSTing to /api/auth/register #1

Description

@149189

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

  1. Start the backend:
(venv) C:\Users\kaust\OneDrive\Documents\GitHub\Singularity\backend> py run.py
  1. 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

  1. Enable detailed exceptions in dev
    Set FastAPI debug for local debugging:

    app = FastAPI(debug=True)
  2. 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.)

  3. 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")
  1. 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.
  2. 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)

  • Catch duplicate key:
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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendbugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions