Back to results for “Security”
Node.js › Git & Project Management

What is the purpose of a .gitignore file in a Node.js project, and what should always be included in it?

Beginner

Answer

.gitignore tells Git which files and directories to never track or commit -- for a Node.js project this critically includes node_modules (which should always be reinstalled from package-lock.json rather than committed, given its size and platform-specific native binaries), .env files containing secrets, build output directories, and log files, keeping the repository focused on source code and configuration rather than generated or sensitive artifacts.
# .gitignore
node_modules/
.env
.env.local
dist/
*.log
coverage/
Real-world example A new contributor accidentally committed their local .env file containing real API keys to a public repository before the team had a proper .gitignore in place, requiring the keys to be rotated immediately and prompting the team to add a comprehensive .gitignore to prevent recurrence.

Common follow-ups: What's the correct process for removing a sensitive file from Git history after it's already been committed and pushed?;Why shouldn't node_modules ever be committed, even though it would technically make cloning and running the project 'simpler'?