Implement Github OAuth login with Next.js and FastAPI #89637
Replies: 1 comment
-
|
Nice walkthrough. The domain separation approach (FastAPI handles OAuth token exchange, Next.js handles cookie setting via server actions) is clean and avoids the common mistake of exposing tokens to the browser. A few thoughts from having built auth systems with similar stacks: What I liked
A few considerations for production use1. Token refresh handlingGitHub OAuth tokens don't expire by default (unless you use the beta expiring tokens feature). But if someone adapts this pattern for other OAuth providers (Google, Microsoft), they'll need refresh token rotation. Worth mentioning where refresh would fit in the flow: 2. CSRF protection on the callbackThe blog mentions the
Without this, the callback endpoint is vulnerable to CSRF where an attacker tricks a user into linking the attacker's GitHub account. 3. Cookie security attributesFor the HttpOnly cookie, make sure all these flags are set in production: # FastAPI side (if setting cookies there)
response.set_cookie(
key="session",
value=session_token,
httponly=True, # not accessible via JavaScript
secure=True, # only sent over HTTPS
samesite="lax", # CSRF protection
max_age=86400, # 24 hours
path="/",
domain=".yourdomain.com" # shared across subdomains if needed
)Or in Next.js server actions: cookies().set('session', sessionToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 86400,
path: '/',
});
4. Alternative approach — same result, fewer round tripsInstead of Next.js calling FastAPI and then setting the cookie in two separate steps, you can have FastAPI return a short-lived signed JWT directly, and Next.js server action just validates and stores it: This reduces the number of calls between Next.js and FastAPI on subsequent requests since the JWT is self-contained. 5. Deployment considerationWhen FastAPI and Next.js are on different domains (e.g.,
The BFF pattern is simpler for cookie management since there's no cross-origin involved. Great article overall — this is a pattern more people should adopt instead of defaulting to NextAuth for everything. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I wrote a practical walkthrough on Github OAuth login with FastAPI and Next.js. It focuses on clean domain separation, HttpOnly cookies, ease of deployment and why handling cookies in Next.js APIs/server actions simplifies OAuth a lot. Includes diagrams and real code.
https://nemanjamitic.com/blog/2026-02-07-github-login-fastapi-nextjs
Interested to hear what others think or if you've taken a different approach.
Beta Was this translation helpful? Give feedback.
All reactions