
Modern applications depend on third-party packages, external APIs, cloud services, and automated deployment pipelines. Although these technologies accelerate development, they also introduce security risks.
A developer might accidentally commit an API key. An npm package might contain a known vulnerability. A pull request might introduce an insecure dependency. Without automated checks, these issues can reach production before anyone notices them.
This is where DevSecOps becomes essential.
DevSecOps integrates security into the software development lifecycle instead of treating security as a final step before deployment.
In this guide, we'll build a practical DevSecOps pipeline using GitHub Actions. We'll implement secret scanning, dependency vulnerability checks, static code analysis, and pull request security checks with copy-paste-ready configuration files.
By the end, you'll have a foundation you can adapt to a Node.js, Express, React, Next.js, or MERN stack application.
1. What Is DevSecOps?
DevSecOps combines development, security, and operations into a continuous process.
Traditional development workflows often focus on writing code, running tests, and deploying applications. Security checks may happen later, sometimes only after a vulnerability has already reached production.
A DevSecOps workflow moves these checks earlier.
For example, when a developer creates a pull request, an automated pipeline can:
Scan the repository for accidentally committed secrets.
Check dependencies for known vulnerabilities.
Analyze source code for potential security issues.
Run linting, type checking, and automated tests.
Block merging when required security checks fail.
Produce reports that help developers investigate findings.
A typical workflow looks like this:
Developer Creates a Pull Request
|
v
GitHub Actions
|
+------+------+
| |
v v
Secret Scan Dependency Scan
| |
v v
Code Analysis npm Audit
| |
+------+------+
|
v
Automated Tests
|
v
Security Review
|
+------+------+
| |
v v
Pass Fail
| |
v v
Ready for Fix Issues
Review
|
v
Merge and DeployThe goal is to detect problems before they become production incidents.
2. Tools We'll Use
Our pipeline will use several tools, each addressing a different security concern.
Tool | Purpose |
|---|---|
GitHub Actions | Automates security checks and CI workflows |
Gitleaks | Detects hardcoded secrets in Git repositories |
npm audit | Identifies known vulnerabilities in npm dependencies |
Dependency Review Action | Checks dependency changes introduced by pull requests |
CodeQL | Analyzes source code for supported security vulnerabilities |
ESLint and tests | Help identify code-quality issues and functional regressions |
These tools complement each other. No single scanner can identify every possible vulnerability.
For example, Gitleaks can detect a committed token, but it does not establish whether an Express endpoint has a broken authorization check. CodeQL may identify certain source-code vulnerabilities, but it does not replace dependency scanning.
A layered approach provides better coverage.
3. Prepare Your GitHub Repository
Before creating the pipeline, ensure your project is committed to a GitHub repository.
For a Node.js application, your project might look like this:
my-node-app/
├── src/
│ ├── controllers/
│ ├── middleware/
│ ├── models/
│ ├── routes/
│ └── services/
├── tests/
├── .github/
│ └── workflows/
├── .gitignore
├── package.json
├── package-lock.json
└── README.mdThe important files are:
package.json: Defines your dependencies and scripts.package-lock.json: Records the resolved dependency tree..github/workflows/: Contains your GitHub Actions workflow files..gitignore: Helps prevent local secrets and generated files from being committed.
Make sure your .gitignore includes sensitive local configuration:
node_modules/
.env
.env.*
!.env.example
dist/
build/
coverage/
*.log
.DS_StoreAdjust these patterns to match your project. For example, do not ignore an environment template that intentionally contains only placeholder values.
Never put actual API keys, database passwords, JWT secrets, or cloud credentials in .env.example.
Important: .gitignore prevents matching untracked files from being added automatically; it does not remove files already tracked by Git.
If a secret has already been committed, removing the file or adding it to .gitignore does not erase the secret from Git history.
4. Set Up Secret Scanning with Gitleaks
Hardcoded secrets are one of the most common security mistakes in software development.
Consider this example:
// config/database.js
import mongoose from "mongoose";
mongoose.connect(
"mongodb+srv://admin:MyRealPassword123@cluster.example.mongodb.net/app"
);This code exposes database credentials directly in the source file.
Anyone with access to the repository may be able to retrieve those credentials.
A safer implementation uses environment variables:
// config/database.js
import mongoose from "mongoose";
export async function connectDatabase() {
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
throw new Error("DATABASE_URL is not configured");
}
await mongoose.connect(databaseUrl);
}Configure DATABASE_URL through your deployment environment or an appropriate secret manager. For GitHub Actions, use GitHub Secrets when a workflow needs access to a credential.
Environment variables help separate configuration from source code, but they are not automatically secure. Avoid printing sensitive values to logs or exposing them to untrusted build steps.
What Is Gitleaks?
Gitleaks is a secret-scanning tool that searches Git repositories for patterns associated with credentials and other sensitive values.
It can help detect accidentally committed:
API keys.
Access tokens.
Database credentials.
Private keys.
Cloud service credentials.
Other strings matching configured secret-detection rules.
Let's add a dedicated GitHub Actions workflow.
Create .github/workflows/secret-scan.yml
name: Secret Scanning
on:
pull_request:
push:
branches:
- main
schedule:
- cron: "0 4 * * 1"
workflow_dispatch:
permissions:
contents: read
jobs:
secret-scan:
name: Scan for exposed secrets
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 0
persist-credentials: false
- name: Run Gitleaks
uses: gitleaks/gitleaks-action@v3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}This workflow runs when a pull request is opened or updated, when code is pushed to main, on a weekly schedule, and when manually triggered.
The full Git history is fetched to support broader scanning. This is particularly useful when investigating secrets that may have appeared in earlier commits.
persist-credentials: false prevents the checkout action from leaving its GitHub authentication credentials configured in Git after checkout.
Licensing note: The Gitleaks GitHub Action has licensing requirements that depend on the account and repository context. In particular, organization-owned repositories may require a Gitleaks license. Check the official action's current documentation before adopting it. If its licensing terms do not fit your project, you can use the Gitleaks CLI directly in a workflow instead.
What Happens When a Secret Is Detected?
If Gitleaks finds a match, the scan can fail and make the security issue visible in the GitHub Actions results.
Your response should be:
Identify the exposed credential.
Revoke or rotate it immediately.
Replace hardcoded credentials with secure configuration.
Review relevant logs and access history.
Investigate whether unauthorized access occurred.
Address the Git history exposure where appropriate.
Never assume that deleting a leaked key from the latest commit makes it safe again. Anyone who accessed the credential while it was valid may still have it.
Also, a clean Gitleaks result does not prove that no secret exists. Scanners can miss credentials that do not match their detection rules.
5. Scan npm Dependencies with npm audit
Most Node.js applications depend on third-party packages.
For example, a MERN application might use:
{
"dependencies": {
"express": "^5.0.0",
"mongoose": "^8.0.0",
"jsonwebtoken": "^9.0.0"
}
}These versions are illustrative, not a recommendation to use particular versions. Select compatible, maintained releases for your project.
Even widely used packages can have vulnerabilities discovered after your application is deployed.
The npm package manager provides a built-in command for checking known vulnerabilities:
npm auditTo fail the command when vulnerabilities at or above a chosen severity are found, use:
npm audit --audit-level=highThis command returns a nonzero exit status when the audit reports vulnerabilities meeting the specified threshold.
The severity threshold controls the exit condition; it does not remove vulnerabilities below that threshold from the report.
Fix Vulnerabilities Carefully
You can inspect the dependency tree:
npm lsYou can also inspect the detailed audit report:
npm auditAfter reviewing the findings, determine whether an update or remediation is appropriate.
For example:
npm updateThis updates eligible dependencies according to the version ranges in your project. It does not guarantee that every vulnerability will be resolved.
Avoid automatically running:
npm audit fix --forcewithout reviewing the proposed changes. Forceful remediation can introduce breaking upgrades and compatibility problems.
For an existing production application, update dependencies in a controlled branch, run regression tests, and review the resulting lockfile changes.
6. Add Dependency Scanning to GitHub Actions
Let's automate the npm audit check.
Create .github/workflows/dependency-scan.yml:
name: Dependency Security Scan
on:
pull_request:
push:
branches:
- main
schedule:
- cron: "0 5 * * 1"
workflow_dispatch:
permissions:
contents: read
jobs:
dependency-scan:
name: Audit npm dependencies
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
- name: Install dependencies
run: npm ci
- name: Audit dependencies
run: npm audit --audit-level=highThis example assumes that your repository contains a compatible package-lock.json and that Node.js 22 is suitable for your application. Change the Node.js version when your project's support requirements differ.
The npm ci command installs dependencies according to the lockfile and is suitable for reproducible CI installations.
If the lockfile is missing or inconsistent with package.json, the installation may fail. Fix the dependency files rather than silently generating a different dependency tree during CI.
Why Run Dependency Scans on a Schedule?
A dependency can become vulnerable even when your application code does not change.
For example:
You deploy an application today.
One of its dependencies is reported vulnerable next week.
Your repository has no new commits.
Your deployed application may still contain the vulnerable package.
Scheduled scans help identify these changes in the vulnerability landscape.
A weekly scan is a useful starting point, but the appropriate frequency depends on your application's risk and operational requirements.
7. Check Pull Request Dependencies Before Merging
npm audit checks the dependency tree installed for the workflow. GitHub's Dependency Review Action addresses a different problem: identifying vulnerable dependencies introduced by a pull request.
This is especially useful when a developer adds or upgrades a package.
For example, a pull request might change:
{
"dependencies": {
"some-package": "1.2.0"
}
}to:
{
"dependencies": {
"some-package": "1.3.0"
}
}A newer version is not automatically safer. The new release might introduce a vulnerability or an unacceptable license.
Create .github/workflows/dependency-review.yml
name: Dependency Review
on:
pull_request:
permissions:
contents: read
jobs:
dependency-review:
name: Review dependency changes
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Review dependencies
uses: actions/dependency-review-action@v5
with:
fail-on-severity: highThis configuration asks the action to fail when the dependency changes introduce vulnerabilities at the configured severity threshold.
Before adopting it, verify the current action version and runner requirements. The Dependency Review Action's availability also depends on repository visibility and GitHub's applicable security feature entitlements. For example, private repositories may require the appropriate GitHub Advanced Security licensing.
The action checks changes between the pull request and its base branch; it is not a substitute for a full audit of every installed dependency.
For additional supply-chain controls, you can configure license policies and other supported dependency review options.
8. Add Static Application Security Testing with CodeQL
Secret and dependency scans do not cover every source-code vulnerability.
For example, an Express application could contain unsafe query construction, an injection vulnerability, or another security problem in its application logic.
Static Application Security Testing (SAST) analyzes source code to identify potential security weaknesses without requiring the application to be running.
GitHub CodeQL supports security analysis for JavaScript and TypeScript projects.
Create .github/workflows/codeql.yml
name: CodeQL Security Analysis
on:
push:
branches:
- main
pull_request:
branches:
- main
schedule:
- cron: "30 4 * * 1"
workflow_dispatch:
permissions:
contents: read
jobs:
analyze:
name: Analyze JavaScript and TypeScript
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: javascript-typescript
queries: security-extended
- name: Perform CodeQL analysis
uses: github/codeql-action/analyze@v4This is a starting configuration for a JavaScript or TypeScript repository. Verify the current CodeQL action version and recommended setup for your repository before deploying it.
The security-extended query suite enables additional security queries beyond the default suite. Depending on the codebase, this can increase analysis time and produce more findings that require review.
The security-events: write permission allows the analysis action to publish supported code-scanning results.
Important: Enabling CodeQL in a workflow does not automatically mean every finding will block a pull request. Configure the repository's code-scanning policies and branch protection or rulesets to enforce the checks you require.
9. Add Code Quality Checks to the Security Pipeline
Security is not limited to vulnerability scanners.
Type errors, broken tests, and unsafe changes can also create reliability and security problems.
For a TypeScript application, your package.json might define scripts like these:
{
"scripts": {
"lint": "eslint .",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"build": "tsc"
}
}These scripts are examples. Adapt them to the commands and tools your project actually uses.
You can add another workflow to run the checks:
Create .github/workflows/quality-checks.yml
name: Code Quality
on:
pull_request:
push:
branches:
- main
permissions:
contents: read
jobs:
quality:
name: Lint, test, and build
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
- name: Install dependencies
run: npm ci
- name: Run lint
run: npm run lint
- name: Run type checking
run: npm run typecheck
- name: Run tests
run: npm test
- name: Build application
run: npm run buildIf the repository uses JavaScript without TypeScript, remove or replace the type-checking step. Likewise, configure the build command to match your frontend or backend application.
For a MERN project, you may need separate jobs for the frontend and backend, especially when they have independent package manifests and lockfiles.
10. Store Secrets Securely in GitHub Actions
Scanning for exposed secrets is only one part of secure CI/CD.
Sometimes a workflow legitimately needs a credential, such as a deployment token or access to a private package registry.
GitHub Actions provides encrypted secrets at repository, organization, and environment levels, subject to the relevant permissions and policies.
For example, you might create a repository secret named:
DEPLOYMENT_TOKENA workflow can reference it like this:
- name: Deploy application
env:
DEPLOYMENT_TOKEN: ${{ secrets.DEPLOYMENT_TOKEN }}
run: npm run deployThe deployment script must actually use this environment variable. This example only demonstrates how the value is passed into the step.
Follow These Rules
Never hardcode tokens in workflow files.
Avoid printing environment variables to logs.
Do not expose production credentials to untrusted pull request code.
Prefer short-lived credentials and workload identity federation when supported.
Restrict who can access and modify repository secrets.
Use GitHub Environments and required approvals for sensitive deployments.
Give workflow tokens only the permissions they need.
For example, a secret-scanning workflow normally needs read-only repository access. It should not need permission to publish releases, change repository settings, or deploy to production.
Least privilege is a core DevSecOps principle: every job should receive only the access required to complete its task.
11. Prevent Pull Requests from Bypassing Security Checks
Creating workflows is not enough if developers can merge changes without waiting for them to finish.
Configure your repository's branch protection rules or rulesets so that the required checks must pass before merging into main.
A practical policy might require:
Secret scanning to pass.
Dependency review to pass.
CodeQL analysis to pass.
Automated tests to pass.
Required human review to be completed.
The exact configuration depends on the repository and the checks GitHub exposes for selection.
Also review how your organization handles failed checks and exceptions. A security gate should have a documented process for investigating findings, fixing vulnerabilities, and approving justified exceptions.
Avoid allowing developers to bypass security controls simply because a pipeline is inconvenient or a vulnerability is difficult to resolve.
For workflows that process untrusted pull request code, be particularly careful with privileged events such as pull_request_target. Combining privileged workflow permissions with execution of untrusted code can expose repository secrets or allow unintended repository modifications.
12. What Should Happen When a Security Check Fails?
A failed pipeline should lead to a clear investigation process.
Secret Scan Failure
Locate the finding without copying the exposed value into tickets or logs.
Determine whether the credential is real.
Revoke or rotate it immediately if it is exposed.
Review possible unauthorized use.
Remove the secret from the source and address relevant Git history.
Rerun the scan after remediation.
Dependency Scan Failure
Identify the affected package and vulnerability advisory.
Determine whether the package is direct or transitive.
Review the affected versions and available fixes.
Update to a compatible, patched version where possible.
Run regression tests.
Document any necessary temporary exception.
CodeQL Failure
Inspect the reported code location.
Determine whether the finding represents a real vulnerability.
Review the execution path and relevant input sources.
Fix the underlying issue.
Add a regression test when practical.
Rerun the analysis and verify the result.
Not every alert represents an exploitable vulnerability, but every significant finding should be reviewed rather than ignored.
13. Common Mistakes to Avoid
Mistake 1: Running Only npm audit
npm audit is useful, but it does not replace secret scanning, source-code analysis, or application security testing.
Better approach: Combine dependency checks with complementary security controls.
Mistake 2: Ignoring Existing Vulnerabilities
A pipeline can fail immediately when introduced into a legacy repository with existing vulnerabilities.
Better approach: Establish a baseline, prioritize critical issues, and create a remediation plan. Avoid suppressing all findings just to obtain a green build.
Mistake 3: Assuming .gitignore Protects Git History
Adding .env to .gitignore does not remove an already committed secret.
Better approach: Rotate exposed credentials and investigate their history and possible misuse.
Mistake 4: Giving Every Workflow Full Repository Permissions
A scanner generally does not need the same permissions as a deployment job.
Better approach: Declare minimal workflow and job permissions.
Mistake 5: Trusting Unpinned Third-Party Actions Blindly
An action is executable code that runs within your CI environment. Its permissions and dependencies matter.
Better approach: Review the action's source and maintenance status. For higher-assurance environments, pin actions to verified full commit SHAs and update them through a controlled process.
Mistake 6: Treating a Green Pipeline as Proof of Security
Automated scanners have limitations and cannot identify every possible application vulnerability.
Better approach: Combine automated checks with code review, security testing, threat modeling where appropriate, and ongoing monitoring.
14. Final DevSecOps Checklist
Use this checklist when preparing your GitHub Actions pipeline for production.
Repository security
Sensitive files are excluded from version control where appropriate.
Real secrets are not stored in source code.
Exposed credentials are rotated promptly.
Repository access follows least privilege.
Automated scanning
Secret scanning runs on pull requests and pushes.
Dependency audits run regularly.
Dependency Review checks new pull request dependencies.
CodeQL or an appropriate SAST tool analyzes the codebase.
Existing findings have an owner and remediation plan.
CI/CD security
Workflow permissions are minimal.
Third-party actions are reviewed and updated.
Untrusted pull request code cannot access production secrets.
Required checks are enforced through branch protection or rulesets.
Production deployment requires the appropriate authorization.
Maintenance
Scheduled scans are enabled.
Security findings are reviewed.
Dependencies are updated in controlled changes.
Pipeline failures are investigated rather than routinely bypassed.
Conclusion
A DevSecOps pipeline helps developers identify security issues earlier and reduces the chance that vulnerable code or exposed credentials reach production.
With GitHub Actions, you can automate secret scanning, dependency vulnerability checks, static code analysis, and quality checks using reusable workflow files.
Start with the controls that address your application's biggest risks, then expand the pipeline as your requirements grow.
For a Node.js or MERN application, a strong starting point is Gitleaks + npm audit + Dependency Review + CodeQL + automated tests.
Remember that security is not a one-time configuration. Keep your workflows maintained, investigate findings promptly, protect credentials, and make security checks part of your everyday development process.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


