🧠 **Auth in [[Intro to Django|Django]] + React**

🧠 Auth in Django + React


1. Session-Based Authentication

(Django’s default way)

  • How it works
    • React sends username + password β†’ Django checks β†’ Django sets a session ID cookie.
    • Browser automatically sends the session cookie on every request.
    • Django knows who you are by looking up the session in the database.
  • Pros
    • Simple (already built into Django).
    • Secure against token theft (cookies are httpOnly + secure if configured).
    • No extra setup (no external library needed).
    • Works well if frontend & backend are on the same domain.
  • Cons
    • More annoying with cross-origin setups (React on localhost:3000, Django on localhost:8000) β†’ need CORS and CSRF configs.
    • Doesn’t scale well for mobile apps / multiple clients (requires cookie/session handling).
    • Harder if you want to expose your API to third-party clients (like a public API).
  • Best when
    • React frontend + Django backend live on same domain.
    • You don’t expect to have mobile apps or external API users.
    • Simpler project, internal tool, school/university project, etc.

2. Token/JWT-Based Authentication

(common for React/SPA/mobile apps)

  • How it works
    • React sends username + password β†’ Django returns a JWT token.
    • React stores the token (usually localStorage or httpOnly cookie).
    • On every request, React sends Authorization: Bearer <token> in headers.
    • Django/DRF validates the token without DB lookup (JWT is self-contained).
  • Pros
    • Frontend-agnostic β†’ works with React, mobile apps, third-party clients.
    • Stateless (no DB lookup needed on every request β†’ better for scaling).
    • Cleaner separation of frontend & backend.
    • Industry standard for modern SPAs.
  • Cons
    • Tokens can be stolen if stored in localStorage (XSS vulnerability). Needs secure handling.
    • Slightly more setup (install djangorestframework-simplejwt or similar).
    • You need to handle token refresh (JWTs usually expire quickly).
  • Best when
    • React frontend + Django backend are on different domains.
    • You want mobile app support in the future.
    • You expect to expose API to external developers.
    • Larger, more scalable projects.

πŸ—οΈ Quick Mindmap Style

AUTH OPTIONS
β”‚
β”œβ”€β”€ Session-Based (Default Django)
β”‚   β”œβ”€β”€ Stores session in DB
β”‚   β”œβ”€β”€ Uses cookies automatically
β”‚   β”œβ”€β”€ Easier to set up
β”‚   β”œβ”€β”€ Harder with CORS/CSRF
β”‚   └── Best for small/same-domain apps
β”‚
└── JWT / Token-Based
    β”œβ”€β”€ Returns JWT to frontend
    β”œβ”€β”€ React stores token
    β”œβ”€β”€ Sent via Authorization header
    β”œβ”€β”€ Stateless (scales better)
    β”œβ”€β”€ Needs secure token handling
    └── Best for modern SPAs, mobile apps, APIs