How to Fix 'git push rejected non-fast-forward' Error Safely
The error [rejected - non-fast-forward] or updates were rejected because the remote contains work that you do not have locally occurs when you attempt to push local commits to a remote branch in Git, but the remote repository contains newer commits that your local branch lacks.
The error [rejected - non-fast-forward] or updates were rejected because the remote contains work that you do not have locally occurs when you attempt to push local commits to a remote branch in Git, but the remote repository contains newer commits that your local branch lacks.
Quick Diagnostics
error: failed to push some refs ... [rejected - non-fast-forward]: The remote repository branch has commits that have not been integrated into your local working copygit pull --rebase origin <branch> to apply remote changes before running git pushStep-by-Step Solution
-
1
Step 1: Fetch and Integrate Remote Updates with Rebase
Instead of executing a standard merge that creates an unnecessary merge commit, use
git pull --rebaseto replay your new local commits on top of the updated remote history:BASH# Replace 'main' with your branch name (e.g., dev or feature/auth) git pull --rebase origin mainIf you prefer inspecting remote changes before rebasing:
BASHgit fetch origin git rebase origin/main -
2
Step 2: Resolve Merge Conflicts If Prompted
If files were modified concurrently in both local and remote commits, Git will pause the rebase process. Open the conflicting files, resolve the markers, and run:
BASH# Stage resolved files git add . # Continue the rebase operation git rebase --continue -
3
Step 3: Push Your Changes Safely
Once your local branch is synchronized and cleanly rebased on top of the remote tip, push your commits:
BASHgit push origin mainIf you rebased existing local commits on a personal feature branch and need to update the remote, avoid destructive
git push --forceand use the safer option:BASHgit push origin main --force-with-lease
Prevention Advice
Recommended security practices:
- Branch Protection Rules: Enable branch protection in GitHub, GitLab, or Bitbucket to prevent direct or forced pushes on default branches like
mainorproduction. - Pull Before Coding: Get into the habit of running
git pull --rebaseat the start of your work session or prior to pushing new code. - Use
--force-with-leaseInstead of--force: The--force-with-leaseflag checks whether someone else has pushed updates to the remote branch before allowing an overwrite.