📝 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
Open your
main.pyfile.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:
statusfor HTTP response codesRedirectResponsefor performing the redirection
from fastapi import status
from fastapi.responses import RedirectResponse🚀 Step 3: Create Root URL Redirect
Locate the root endpoint in
main.py(usually@app.get("/")).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
Run your FastAPI application:
uvicorn app.main:app --reloadOpen your browser and navigate to
127.0.0.1:8000.Check behavior:
If logged in → Redirected to To-Do home page
If logged out → Redirected to Login page
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.