Skip to content

Git and GitHub Best Practices: A Complete Guide

A practical guide to Git and GitHub best practices: setup, branching, commits, pull requests, branch rulesets, security, releases and recovery.

Technology Engineering 15 min read Add as preferred source
An editorial illustration of branching paths of light merging into a single glowing trunk line
An editorial illustration of branching paths of light merging into a single glowing trunk line

The best Git and GitHub workflow is simple: short-lived branches, small commits with clear messages, reviewed pull requests, a protected default branch, and automation that stops secrets and broken builds before they reach main. None of this is exotic. The hard part is doing all of it consistently, so this guide turns each practice into a setting, a command or a rule you can adopt today. If you want the underlying model of how Git works, the free Pro Git book is the best companion[1].

Area Do this Avoid this
Setup Configure identity, sensible defaults and commit signing once Committing with a wrong or missing email
Branching One short-lived branch per change, branched from main Long-lived feature branches that drift for weeks
Commits Small, atomic, with a message that explains why “fix stuff”, “wip”, mixed unrelated changes
Pull requests Small, described, linked to an issue, reviewed 2,000-line PRs with no description
Merging Pick one default strategy per repository Mixing squash, rebase and merge randomly
History Rewrite only your own unshared work git push --force to a shared branch
Protection Rulesets on the default branch Direct pushes to main
Security Push protection, pinned Actions, least-privilege tokens Secrets in the repo, tags like @v4 for third-party Actions

Wrong author information is the most common cause of messy history and “unverified” commits. Set your identity, then turn on a few defaults that remove friction later.

Terminal window
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global pull.ff only # never create surprise merge commits on pull
git config --global fetch.prune true # drop remote-tracking branches that were deleted
git config --global push.autoSetupRemote true # first push sets upstream automatically (Git 2.37+)
git config --global rebase.autoSquash true # honor fixup! and squash! commits
git config --global rerere.enabled true # remember conflict resolutions and reuse them
git config --global merge.conflictStyle zdiff3 # clearer conflict markers (Git 2.35+)

Use the email address that is verified on your GitHub account, or GitHub cannot link your commits to you.

Signed commits prove that a commit really came from you. You can sign with GPG, S/MIME or an SSH key, and SSH signature verification needs Git 2.34 or later[2]. If you already use SSH to authenticate, reusing the same style of key is the least effort.

Terminal window
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
git config --global tag.gpgsign true

Then add the same public key to GitHub as a signing key under your account’s SSH and GPG keys settings. After that, your commits show a “Verified” badge. If signing silently fails on your machine, check that your key is loaded in ssh-agent; a missing agent entry is a common cause of unverified commits.

  • Turn on two-factor authentication or passkeys for your GitHub account.
  • Authenticate with SSH keys or a credential manager such as GitHub CLI (gh auth login). Never paste a personal access token into a remote URL, because it ends up in .git/config and shell history.
  • Give tokens the narrowest scope and shortest lifetime that works.

A repository that is easy to understand gets better contributions. Add these files at the start, not after the first incident.

File Purpose
README.md What the project is, how to run it, how to test it
LICENSE What others may legally do with the code
.gitignore Keeps build output, dependencies and local secrets out of Git
.gitattributes Normalizes line endings and marks generated or binary files
CONTRIBUTING.md Branch, commit and PR conventions for contributors
SECURITY.md How to report a vulnerability privately
.github/CODEOWNERS Who must review changes to which paths
.github/pull_request_template.md A checklist that appears in every PR
.github/dependabot.yml Automated dependency and Actions updates

A starter .gitignore for a TypeScript project deployed on Cloudflare Workers looks like this:

node_modules/
dist/
.wrangler/
.env
.env.*
!.env.example
.dev.vars
*.log
.DS_Store

Three habits matter more than the file itself:

  1. Commit a .env.example with placeholder values and ignore the real .env and .dev.vars files.
  2. Commit your lockfile (for example bun.lock) so every machine and CI run installs the same dependency versions.
  3. Keep large binaries out of Git. Use Git LFS or object storage, because history keeps every version of a file forever.

GitHub flow is a lightweight, branch-based workflow: you create a branch, make changes, open a pull request, address review comments, merge, and delete the branch[3]. Your branch is a safe place to change things, and nothing reaches the default branch until you merge[3].

The cycle, step by step:

  1. Branch from the latest main.
  2. Commit small changes to the branch.
  3. Open a pull request.
  4. Fix anything the review or checks flag, then push more commits.
  5. Merge into main once checks pass and the review is approved.
  6. Delete the branch and deploy.
Several thin light branches splitting from a main trunk and rejoining it after a short distance
Short-lived branches leave the trunk and return quickly, so the trunk never drifts far from any of them.

Rules that make the model work:

  • Keep main deployable. Everything on it should have passed review and checks.
  • Branch from the latest main and keep branches short-lived, measured in hours or days, not weeks. The longer a branch lives, the harder the merge.
  • Name branches for their purpose. A short, descriptive name lets collaborators see ongoing work at a glance[3]. A type/description pattern works well: feat/passkey-login, fix/session-null-check, docs/api-examples.
  • Make a separate branch for each set of unrelated changes. It makes review easier and means a delay in one change does not hold up the others[3].
  • Delete the branch after merging. It signals the work is done and prevents anyone from building on a stale branch[3].

Long-lived release branches (the classic Git Flow model) are justified only when you must maintain several released versions at once. For a web service or SaaS product that deploys continuously, they add overhead without much benefit. That last point is a judgment call, not a rule, so adapt it to your release process.

Ideally, each commit contains an isolated, complete change, which makes it easy to revert if you take a different approach[3]. GitHub’s own example: put a variable rename in one commit and the new tests in another, so you can later revert the rename and keep the tests[3].

Practical habits:

  • Stage deliberately with git add -p so you commit hunks, not whole messy files.
  • Review what you are about to commit with git diff --staged.
  • Fix up earlier commits with git commit --fixup <sha> and let rebase.autoSquash fold them in during an interactive rebase.
  • Never commit generated files, secrets or debugging leftovers.

Conventional Commits is a lightweight convention on top of commit messages, and it makes history readable by both people and tools[4]. The structure is a type, an optional scope and a short description, then an optional body and footers:

feat(auth): add passkey login
Passkeys replace password entry on supported browsers. The password
flow stays available as a fallback.
Refs: #214

The fix type maps to a patch release, feat to a minor release, and a commit with a BREAKING CHANGE to a major release[4]. A ! before the colon, as in feat(api)!: remove v1 endpoints, flags a breaking change in the header. Teams commonly add types such as docs, refactor, perf, test, build and ci, but the specification itself does not mandate them[4].

Good message habits regardless of format:

  • Use the imperative mood: “add passkey login”, not “added” or “adds”.
  • Keep the subject short, roughly 50 characters, and wrap the body near 72. This is a long-standing convention, not something Git enforces.
  • Explain why in the body. The diff already shows what changed.
  • Reference the issue in a footer, such as Refs: #214.

Nobody needs to be perfect on every commit. If you use a squash-based workflow, maintainers can clean up commit messages as they merge, so casual contributors carry no extra workload[4].

A pull request is a request for feedback, and review is valuable enough that some repositories require an approving review before merging[3].

  • Small and focused. One concern per PR. If the description needs the word “and” three times, split it.
  • A real description. Include a summary of the changes and the problem they solve; you can add images, links and tables to help[3].
  • Linked to its issue. If you link with a closing keyword, the issue closes automatically when the pull request merges[3].
  • Marked as draft when unfinished. A draft PR is the right way to ask for early feedback[3].
  • Green before review. Let CI run first so reviewers spend time on design, not on typos and failing tests.
  • Self-reviewed. Read your own diff in the GitHub UI before requesting anyone else’s time.

A pull request template keeps this consistent:

## What and why
Summary of the change and the problem it solves.
## How to test
Steps or commands a reviewer can run.
## Checklist
- [ ] Tests added or updated
- [ ] Docs updated if behavior changed
- [ ] No secrets or personal data in the diff
- [ ] Linked issue (Closes #)

  • Review the design and risk first, then the details.
  • Distinguish blocking comments from suggestions and questions.
  • Use CODEOWNERS so the right people are requested automatically.
  • Respond to review comments by pushing more commits to the same branch; the pull request updates automatically[3].

GitHub offers three ways to merge a pull request. Choosing one default per repository keeps history predictable.

Strategy What lands on the default branch Best when Watch out for
Squash and merge One new commit for the whole PR Branches contain noisy “wip” commits Individual commit history is lost from main
Rebase and merge Each PR commit, replayed linearly Every commit is already atomic and well described Commit hashes change; a messy branch pollutes main
Merge commit All commits plus a merge commit You want to preserve branch topology Non-linear history is harder to read and bisect

A sensible default for most application repositories is squash merge with the pull request title written as a Conventional Commit, because the PR title then becomes the clean commit message. Enforcing a linear history on a branch prevents merge commits, so pull requests must use squash or rebase merging[5]. Before you can require linear history, the repository itself must allow squash or rebase merges[5].

Rewriting history is powerful and safe only under one condition: the commits are yours and nobody else has built on them. A feature branch you alone push to qualifies. main never does.

Terminal window
# Tidy your local commits before opening or updating a PR
git fetch origin
git rebase -i origin/main
# Publish the rewritten branch safely
git push --force-with-lease

Plain --force overwrites whatever is on the remote. --force-with-lease adds a safety check: the push fails unless the remote branch still has the value you expect[6]. That protects a teammate’s newer commit from being erased. One caveat: the lease only knows about what you last fetched, so a background git fetch from an editor plugin can weaken the protection. Git also offers --force-if-includes to tighten the check further, which is worth adding if your tooling fetches automatically.

Know which undo tool fits:

  • git revert <sha> adds a new commit that undoes an old one. Use it for anything already pushed to a shared branch.
  • git reset moves the branch pointer and can discard work. Use it only on local, unpublished commits.
  • git reflog is your safety net. Git records where HEAD has been, so a “lost” commit can usually be recovered from it for a while after you drop it.

Good habits fail under deadline pressure. Rulesets turn them into rules the platform enforces. You can create branch or tag rulesets to control how users interact with selected branches and tags, and you can let specific roles, teams or GitHub Apps bypass them[5]. Rulesets are available for public repositories on GitHub Free, and for public and private repositories on paid plans[5].

A strong baseline for the default branch follows. Every rule below except status checks and force-push blocking is documented in the GitHub rulesets reference[5].

Rule Why it helps
Restrict deletions Stops main from being deleted by accident
Block force pushes Protects shared history from being rewritten
Require a pull request before merging Forces review and checks instead of direct pushes
Require approvals (at least one) A second pair of eyes on every change
Dismiss stale approvals when new commits are pushed Prevents an approved PR from being “hijacked” with unreviewed changes
Require code owner review Routes sensitive paths to the right reviewers
Require status checks to pass Makes failing tests block the merge
Require linear history Keeps history readable; forces squash or rebase merges
Require signed commits Only verified, signed commits can be pushed
Require a merge queue Tests each PR against the latest base before it lands

Two practical notes. First, keep the bypass list tiny, ideally just repository admins for emergencies, and treat every bypass as something to review later. Second, introduce rules gradually: turn on pull requests and status checks first, and add signed commits or merge queues once the team is comfortable.

Push protection is a secret scanning feature that blocks a push when it detects a supported secret, rather than alerting you after the secret is already committed[7]. It covers pushes from the command line, commits in the GitHub UI, file uploads and REST API requests[7]. Contributors with write access can bypass it by choosing a reason, and GitHub records that bypass, so review those alerts[7]. You can also turn on push protection for your own account, which protects your pushes to any public repository[7].

If a secret does reach a repository:

  1. Revoke and rotate it immediately. Assume it is compromised, because removing it from the code does not remove it from clones, forks or caches.
  2. Remove it from the current code and, only if needed, from history.
  3. Check logs of the affected service for misuse.
  4. Add a rule or hook so the same mistake is caught earlier next time.

Third-party Actions run with access to your repository, so treat them as dependencies. Git tags can be moved, so a reference such as @v4 can silently change. Pinning an Action to a full-length commit SHA means you always run exactly the code you reviewed[8]. Add a version comment so humans and Dependabot can see which release the SHA represents.

name: ci
on:
pull_request:
push:
branches: [main]
permissions:
contents: read # least privilege by default
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@FULL_LENGTH_COMMIT_SHA # vX.Y.Z
- uses: oven-sh/setup-bun@FULL_LENGTH_COMMIT_SHA # vX.Y.Z
- run: bun install --frozen-lockfile
- run: bun run typecheck
- run: bun test

Replace each FULL_LENGTH_COMMIT_SHA with the 40-character commit SHA of the release you reviewed. Then let Dependabot keep them current:

.github/dependabot.yml
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly

Other Actions habits that pay off: set permissions explicitly instead of relying on broad defaults, never print secrets in logs, and do not run untrusted pull request code with write-scoped tokens.

Git hooks are scripts that run at points such as before a commit or when a message is entered; Pro Git covers them in its chapter on customizing Git[1]. Common uses are a pre-commit hook that runs the formatter, linter and type-checker, and a commit-msg hook that validates Conventional Commit messages. Tools such as Husky or lefthook make hooks shareable across a team.

The key point: hooks are a convenience, not enforcement. They live on each developer’s machine and can be skipped with --no-verify. Anything that must be true, such as passing tests or a valid PR title, belongs in CI and in required status checks, where it cannot be skipped.

  • Use Semantic Versioning: patch for fixes, minor for backward-compatible features, major for breaking changes. Conventional Commits maps neatly onto this and can drive changelogs and version bumps automatically[4].
  • Create annotated tags for releases so they carry an author, date and message: git tag -a v1.4.0 -m "Release 1.4.0". Use git tag -s to sign them.
  • Publish releases from the tag, for example with gh release create v1.4.0 --generate-notes.
  • For urgent fixes, branch from the released tag, fix, review and merge through the normal pull request path; do not skip review because it is an emergency.

Situation Command
Undo the last commit but keep the changes git reset --soft HEAD~1
Fix the message of an unpushed commit git commit --amend
Unstage a file git restore --staged <file>
Discard local edits to a file git restore <file>
Undo a commit that is already pushed git revert <sha>
Recover a commit you “lost” git reflog, then git switch -c rescue <sha>
Park unfinished work git stash push -u -m "describe it"
Find the commit that introduced a bug git bisect start, then mark commits good or bad
Commit landed on the wrong branch git switch -c correct-branch, then reset the wrong branch to its remote state
Abort a messy rebase git rebase --abort

Before any destructive command, run git status and git log --oneline -5, and consider creating a backup branch with git branch backup/before-rewrite.

  • Committing directly to main “just this once”.
  • Using git push --force on a shared branch.
  • Giant pull requests that mix refactors, features and formatting.
  • Commit messages like “update”, “fix” or “final-final”.
  • Long-lived branches that are never rebased or merged.
  • Committing .env files, API keys or database dumps.
  • Referencing third-party Actions by mutable tags without reviewing them.
  • Treating local hooks as the only quality gate.
  • Leaving merged branches undeleted.

Work through this list per repository, in roughly this order:

  • Identity, defaults and commit signing configured on every developer machine
  • README, LICENSE, .gitignore, CONTRIBUTING, SECURITY and a PR template present
  • Default branch protected by a ruleset requiring PRs, approvals and status checks
  • One merge strategy chosen and the others disabled in repository settings
  • CI runs tests and type checks on every pull request
  • Push protection and secret scanning enabled
  • Actions pinned to full commit SHAs and permissions set explicitly
  • Dependabot configured for Actions and dependencies
  • CODEOWNERS defined for sensitive paths
  • Release process documented, with annotated tags and generated notes

Adopt these gradually. A team that reliably does five of them beats a team that writes a ten-point policy and ignores it.

  1. ^ a b Chacon, Scott and Straub, Ben. Pro Git, 2nd edition. Apress, 2014. Free online. https://git-scm.com/book/en/v2
  2. ^ GitHub Docs. “Telling Git about your signing key.” https://docs.github.com/en/authentication/managing-commit-signature-verification/telling-git-about-your-signing-key
  3. ^ a b c d e f g h i j k l GitHub Docs. “GitHub flow.” https://docs.github.com/en/get-started/using-github/github-flow
  4. ^ a b c d e Conventional Commits. “Conventional Commits 1.0.0.” https://conventionalcommits.org/en/v1.0.0
  5. ^ a b c d e GitHub Docs. “Available rules for rulesets.” https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets
  6. ^ Git documentation. “git-push: –force-with-lease.” https://git-scm.com/docs/git-push
  7. ^ a b c d GitHub Docs. “About push protection.” https://docs.github.com/en/code-security/concepts/secret-security/about-push-protection
  8. ^ GitHub Docs. “Secure use reference” (GitHub Actions). https://docs.github.com/en/actions/reference/security/secure-use

Frequently asked questions

What is the best Git branching strategy for most teams?

For most teams, GitHub flow is enough: keep the default branch deployable, create a short-lived branch for each change, open a pull request, get a review and passing checks, merge, then delete the branch. Add long-lived release branches only if you must support several versions at once.

Should I squash, rebase or create a merge commit on GitHub?

Use squash merge when a branch has noisy commits and you want one clean commit on the default branch. Use rebase merge when every commit is already atomic and well described. Use a merge commit when you want to preserve the branch topology. Requiring linear history allows only squash or rebase merges.

How do I safely force push after a rebase?

Use git push --force-with-lease instead of --force. It only overwrites the remote branch if it still points to the commit you last fetched, so it will not erase a teammate's newer work. Only rewrite history on branches that you own, never on the default branch.

How do I protect the main branch on GitHub?

Create a ruleset for the default branch that requires a pull request with at least one approval, requires status checks to pass, restricts deletions and force pushes, and optionally requires linear history or signed commits. Keep the bypass list as small as possible.

What should I do if I commit a secret to GitHub?

Revoke and rotate the secret immediately, because anyone who saw it may already have copied it. Then remove it from the code, and enable push protection so supported secret types are blocked before future pushes land.

Do I need to sign my Git commits?

It is not required, but signing lets GitHub mark your commits as verified and lets a ruleset enforce signed commits. Signing with an SSH key is the simplest setup and needs Git 2.34 or later.

You're offline Check your connection.