FastAPI - Beginner to Pro / Project 5 - Full Stack Application

FastAPI Full stack - Home Page Redirection

📝 Introduction: Redirecting the Root URL

In this lesson, we’ll make sure that when users visit the root URL (127.0.0.1:8000), they are automatically redirected to the correct page:

  • Authenticated users → To-Do home page

  • Unauthenticated users → Login page

This ensures users never see a random landing page and improves security and user experience.


🏗️ Step 1: Update main.py

  1. Open your main.py file.

  2. Remove unused Jinja2 template references for the root page. We won’t render a template for this redirect.

# Remove or comment out:
# from fastapi.templating import Jinja2Templates
# templates = Jinja2Templates(directory="templates")

🔄 Step 2: Import Required Modules

We need two things from FastAPI:

  • status for HTTP response codes

  • RedirectResponse for performing the redirection

from fastapi import status
from fastapi.responses import RedirectResponse

🚀 Step 3: Create Root URL Redirect

  1. Locate the root endpoint in main.py (usually @app.get("/")).

  2. Replace the old template rendering logic with a redirect:

@app.get("/")
async def root(request: Request):
    # Check for valid authentication cookie
    token = request.cookies.get("access_token")

    if token:
        # Authenticated users go to the to-dos page
        return RedirectResponse(url="/todos/todo-page", status_code=status.HTTP_302_FOUND)
    else:
        # Unauthenticated users go to login page
        return RedirectResponse(url="/auth/login-page", status_code=status.HTTP_302_FOUND)

✅ Step 4: Test the Redirect

  1. Run your FastAPI application:

uvicorn app.main:app --reload
  1. Open your browser and navigate to 127.0.0.1:8000.

  2. Check behavior:

    • If logged in → Redirected to To-Do home page

    • If logged out → Redirected to Login page

  3. Test logging out and revisiting the root URL to confirm the redirection works correctly.


🎯 Step 5: Summary

  • We removed the landing page template for the root URL.

  • We implemented a redirect based on authentication using RedirectResponse.

  • Now, users can only access the main app pages if authenticated, improving both UX and security.

  • Combined with our To-Do CRUD, login, registration, and logout features, the application is now full-stack and production-ready.