[Git] Error: failed to push some refs — Updates were rejected because the remote contains work that you do not have locally — How to Fix It

Summary

error: failed to push some refs happens when your local branch is behind the remote branch. Git prevents overwriting remote commits that you haven’t yet fetched. To fix this, synchronize your local and remote histories by pulling or rebasing before pushing again.

Context

When multiple developers push to the same branch, Git enforces “fast-forward only” pushes. This ensures no one overwrites others’ work accidentally. If your local commit history diverges from the remote, Git blocks the push until you reconcile the changes.

Probable Cause

  • Another collaborator pushed commits to the same branch before you.
  • Your branch is behind remote (you haven’t pulled recent changes).
  • You rebased or amended commits already pushed.
  • Remote branch is protected against force pushes.

Quick Fix

  1. Confirm your branch:
    git status
  2. Fetch remote updates:
    git fetch origin
  3. Compare histories:
    git log main..origin/main --oneline      # Remote commits
    git log origin/main..main --oneline      # Local commits
  4. Rebase or merge to align histories:
    # Rebase (preferred)
    git pull --rebase origin main
    
    # Or merge directly
    git pull origin main
  5. Resolve conflicts (if any):
    git status
    # Edit conflicted files, then:
    git add .
    git rebase --continue
  6. Push again after syncing:
    git push origin main

Example

# Error
$ git push origin main
error: failed to push some refs to 'https://github.com/user/repo.git'
hint: Updates were rejected because the remote contains work that you do not have locally.

# Fix
$ git pull --rebase origin main
$ git push origin main
Everything up-to-date

Alternate Scenarios

  • Team workflow: Someone pushed before you — rebase first, then push.
  • Solo project: If safe, you can overwrite remote history:
    git push --force-with-lease
    (Use carefully — this rewrites commits.)
  • Protected branches: If main is protected, push to a feature branch and create a pull request instead.

Pitfalls & Debug

  • Symptom → Push fails even after pull. Fix → Use git fetch --all and git rebase origin/main.
  • Symptom → Conflicts during rebase. Fix → Resolve manually, then git rebase --continue.
  • Symptom → Repeated rejection. Fix → Check git remote -v — confirm you’re pushing to the correct remote.

Verification & Next Steps

# Check alignment
git fetch --all
git log --graph --oneline --all

# Verify status
git status

Best Practices

  • Always pull or fetch before pushing new work.
  • Use git pull --rebase for linear history.
  • Prefer --force-with-lease over --force — it’s safer.
  • Push to feature branches to avoid conflicts on main.

Sources

Git Documentation — git push

Git Documentation — git pull

Stack Overflow — failed to push some refs

Labels

Tool/Git, OS/Cross-platform, Topic/Remote Synchronization