Cookie not showing up in browser after FastAPI OAuth redirect

I’m working on a FastAPI app with Google OAuth login. When users authenticate, I try to set a cookie with their auth token, but the cookie never shows up in the browser. I’m using a redirect response after the OAuth callback and trying to attach the cookie to it. The redirect works fine but the cookie just disappears. Are there better ways to pass authentication tokens to the frontend securely?

@app.get("/auth/google")
async def start_google_auth():
    oauth_flow = Flow.from_client_secrets_file(
        SECRETS_FILE,
        scopes=["openid", "email", "profile"],
        redirect_uri=config.oauth_callback_url
    )
    auth_url, session_state = oauth_flow.authorization_url(
        access_type='offline',
        include_granted_scopes='true'
    )
    
    return RedirectResponse(auth_url)

@app.get("/auth/callback")
async def handle_oauth_callback(
    auth_code: str,
    resp: Response,
    db: AsyncSession = Depends(get_db)
):
    try:
        oauth_flow = Flow.from_client_secrets_file(
            SECRETS_FILE,
            scopes=["openid", "email", "profile"],
            redirect_uri=config.oauth_callback_url
        )
        
        oauth_flow.fetch_token(code=auth_code)
        creds = oauth_flow.credentials
        token_info = id_token.verify_oauth2_token(
            creds.id_token, 
            requests.Request(), 
            config.google_client_id
        )
        
        user_data = UserSchema(
            full_name=token_info.get('name'), 
            email=token_info.get('email'), 
            password="", 
            verified=True
        )
        
        auth_service = UserAuthService(db, user_data, from_google=True)
        
        if await auth_service.user_exists():
            if not await auth_service.is_verified():
                await auth_service.verify_user()
        else:
            await auth_service.register_user()
        
        token_expiry = timedelta(minutes=45)
        jwt_token = generate_jwt_token(
            data={"email": user_data.email}, 
            expires_delta=token_expiry
        )
        
        resp.set_cookie(
            key="jwt_token", 
            value=jwt_token, 
            httponly=True,
            domain='localhost'
        )
        
        return RedirectResponse(
            url="http://localhost:3000/dashboard", 
            status_code=302
        )
        
    except Exception as error:
        raise HTTPException(
            status_code=400, 
            detail=f"OAuth error: {str(error)}"
        )

I’m setting up the Response object and adding the cookie before the redirect, but it’s not working. What could be going wrong here?

The problem is you’re mixing Response objects with RedirectResponse. When you return RedirectResponse, it creates a completely new response that doesn’t carry over any cookies you set on the original resp parameter. I hit this same issue with FastAPI auth. Create the RedirectResponse first, then set the cookie directly on it: python redirect_response = RedirectResponse( url="http://localhost:3000/dashboard", status_code=302 ) redirect_response.set_cookie( key="jwt_token", value=jwt_token, httponly=True, domain='localhost' ) return redirect_response This way the cookie gets attached to the actual response you’re returning, not some separate Response object that gets tossed.

Check your domain setting - localhost can cause issues depending on setup. Try removing the domain parameter completely or set it to None. FastAPI usually handles this better without explicit localhost domains. Also verify your frontend’s actually running on localhost:3000, not 127.0.0.1, since browsers treat those as different domains for cookies.

interesting setup! check your network tab in dev tools - is the set-cookie header actually being sent? the browser might be blocking it because of samesite policies. try adding samesite='lax' to your cookie params. also, does it work if you test without the redirect first?