When working with Git, one of the most common frustrations developers face is the dreaded push rejected error. This usually happens when your local branch is out of sync with the remote branch. Let’s break down why this occurs and how to fix it.
Why Does Git Reject a Push?
Git prevents you from overwriting changes that exist on the remote but not in your local branch. This ensures that you don’t accidentally erase someone else’s work or lose commits. The error message often looks like this:
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'https://github.com/...'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally.
Common Fixes
1. Rebase (Recommended) : If you want to keep a clean, linear history:
git pull origin main --rebase
# resolve conflicts if any
git rebase --continue
git push origin main
This approach reapplies your local commits on top of the remote branch.
2. Merge : If you don’t mind merge commits:
git pull origin main
# resolve conflicts if any
git push origin main
This creates a merge commit combining both histories.
3. Force Push (Dangerous) : If you want to overwrite the remote branch entirely:
git push origin main --force
⚠️ Warning: This will erase remote commits not present locally.
What About --allow-unrelated-histories?
This option is used when two repositories don’t share a common history (e.g., you initialized locally and then connected to a remote with its own commits). It forces Git to merge unrelated histories. In most cases, you don’t need this if your local and remote already share a history.
Best Practices:
Use rebase for a clean history.
Use merge if you prefer explicit merge commits.
Avoid force push unless you’re absolutely sure.
Reserve --allow-unrelated-histories for truly separate repositories.
Conclusion
A rejected push isn’t a blocker—it’s Git protecting your project’s history. By understanding when to rebase, merge, or force push, you can resolve these errors confidently and keep your repository healthy.
Top comments (0)