A powerful library to analyze Next.js applications, generate documentation, and perform security analysis. Designed to be clean, scalable, and extensible for public use.
- Route Discovery: Automatically scans Next.js projects (both Pages Router and App Router) to discover all routes and API handlers
- Documentation Generation: Generates comprehensive API documentation in multiple formats (Markdown, HTML, JSON)
- Security Analysis: Identifies security vulnerabilities and bad practices using built-in rules
- Plugin System: Easily extensible via plugins to add custom rules and documentation formatters
- CI/CD Integration: Seamlessly integrates into CI/CD pipelines with SARIF output and exit codes
# Clone the repository
git clone https://github.com/minaa66/nextjs-analyzer.git
cd nextjs-analyzer
# Install dependencies
npm install
# Build the project
npm run build
# Link globally to use as CLI
npm linkNow you can use the CLI anywhere:
nextjs-analyzer /path/to/your/nextjs-app- Download the latest release from the releases page
- Extract the archive
- Follow the build steps above
After installing and linking, analyze your Next.js project:
# Basic analysis
nextjs-analyzer /path/to/nextjs-app
# Generate HTML documentation
nextjs-analyzer /path/to/nextjs-app --format html --output docs/api.html
# Generate SARIF report for GitHub Code Scanning
nextjs-analyzer /path/to/nextjs-app --format sarif --output results.sarif.json
# Only security analysis with medium threshold
nextjs-analyzer /path/to/nextjs-app --no-docs --threshold medium
# Skip security analysis
nextjs-analyzer /path/to/nextjs-app --no-securityUsage: nextjs-analyzer [options] <project-path>
Analyze Next.js applications for routes, documentation, and security issues
Arguments:
project-path Path to the Next.js project to analyze
Options:
-o, --output <file> Output file path (default: "report.md")
-f, --format <format> Output format (md, html, json, sarif) (default: "md")
-c, --config <file> Path to configuration file
-p, --plugin <path> Plugin path (can be specified multiple times)
-i, --ignore <pattern> Ignore pattern (can be specified multiple times)
--threshold <level> Minimum severity to fail (low, medium, high, critical) (default: "low")
--no-security Skip security analysis
--no-docs Skip documentation generation
--json Output as JSON (shorthand for -f json)
--sarif Output as SARIF (shorthand for -f sarif)
-v, --verbose Enable verbose logging
-s, --silent Silent mode (no output except errors)
-h, --help Display help for command
-V, --version Display version number
API Routes
| Route | Methods | Parameters | Router | Description |
|-------|---------|------------|--------|-------------|
| /api/users | GET, POST | - | app | User management |
| /api/users/:id | GET, PUT, DELETE | :id | app | Single user operations |
| /api/products | GET, POST | - | app | Product listing |
Page Routes
| Route | Parameters | Router | Description |
|-------|------------|--------|-------------|
| / | - | app | Home page |
| /products/:slug | :slug | app | Product detail |
| /cart | - | app | Shopping cart |
High (3)
- hardcoded-secrets: Potential API key in /src/config.ts:15
- missing-authentication: API route lacks auth checks /src/app/api/admin/route.ts:5
- xss-vulnerabilities: dangerouslySetInnerHTML in /src/components/HtmlContent.tsx:12
import {
createFileScanner,
createASTParser,
createDataExtractor,
createSecurityAnalyzer,
createDocumentationGenerator,
} from 'nextjs-analyzer';
async function analyzeProject(projectPath: string) {
// Scan files
const scanner = createFileScanner();
const files = await scanner.scan(projectPath);
// Parse files
const parser = createASTParser();
const sourceFiles = parser.loadFiles(files);
// Extract routes
const extractor = createDataExtractor({ projectPath });
const { routes, middleware, config } = await extractor.extractAll(sourceFiles);
// Run security analysis
const securityAnalyzer = createSecurityAnalyzer();
const findings = securityAnalyzer.analyze(sourceFiles, {
projectPath,
sourceFiles,
routes,
config,
middleware,
});
// Generate documentation
const docGenerator = createDocumentationGenerator();
const markdown = docGenerator.generateMarkdown(routes);
return { routes, findings, markdown };
}Create a nextjs-analyzer.config.js file in your project root:
module.exports = {
output: 'report.md',
format: 'md',
rules: {
'hardcoded-secrets': 'error',
'sql-injection': 'error',
'missing-authentication': 'warning',
'xss-vulnerabilities': 'error',
'insecure-headers': 'warning',
'client-side-env': 'warning',
},
plugins: ['./custom-rules.js'],
ignore: ['**/generated/**', '**/dist/**'],
threshold: 'medium',
};The following security rules are included:
| Rule | Severity | Description |
|---|---|---|
hardcoded-secrets |
High | Detects hardcoded credentials (passwords, API keys, tokens) in source code |
sql-injection |
Critical | Identifies raw SQL query construction using string concatenation or interpolation |
missing-authentication |
High | Flags API routes that lack authentication checks |
xss-vulnerabilities |
High | Detects use of dangerouslySetInnerHTML or innerHTML assignments |
insecure-headers |
Medium | Checks if next.config.js sets recommended security headers |
client-side-env |
Medium | Detects usage of process.env in client-side components |
Create a custom plugin:
// my-plugin.js
module.exports = {
name: 'my-custom-plugin',
version: '1.0.0',
description: 'Custom security rules for my project',
apply(context) {
// Register a custom security rule
context.registerRule({
name: 'no-eval',
severity: 'high',
description: 'Detects usage of eval()',
run(sourceFile) {
const findings = [];
// ... rule implementation
return findings;
},
});
// Register a custom formatter
context.registerFormatter('csv', (routes) => {
return routes.map(r => `${r.path},${r.methods.join(';')}`).join('\n');
});
},
};Use the plugin:
nextjs-analyzer /path/to/nextjs-app --plugin ./my-plugin.jsname: Security Analysis
on: [push, pull_request]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install nextjs-analyzer
run: |
git clone https://github.com/your-username/nextjs-analyzer.git
cd nextjs-analyzer
npm install
npm run build
npm link
- name: Run analysis
run: nextjs-analyzer ./ --format sarif --output results.sarif.json --threshold medium
- name: Upload SARIF results
uses: github/codeql-action/upload-sarif@v2
if: always()
with:
sarif_file: results.sarif.json0: Analysis completed with no issues above the threshold1: Issues found at or above the specified threshold level
- Pages Router (
pages/) - App Router (
app/) - API Routes (both routers)
- Dynamic routes (
[id],[...slug],[[...optional]]) - Middleware
- Data fetching methods (
getServerSideProps,getStaticProps, etc.) next.config.jsparsing
# Clone the repository
git clone https://github.com/your-username/nextjs-analyzer.git
cd nextjs-analyzer
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
# Run linting
npm run lint
# Format code
npm run formatnextjs-analyzer/
├── src/
│ ├── index.ts # Main entry point
│ ├── cli.ts # CLI implementation
│ ├── scanner/ # File scanning logic
│ ├── parser/ # AST parsing with ts-morph
│ ├── extractor/ # Route/middleware/config extraction
│ ├── security/ # Security analysis rules
│ ├── docs/ # Documentation generators
│ ├── output/ # Output formatting
│ ├── plugins/ # Plugin system
│ ├── types/ # TypeScript types
│ └── utils/ # Utility functions
├── tests/ # Unit tests
├── package.json
└── tsconfig.json
MIT
Contributions are welcome! Please read our contributing guidelines before submitting a pull request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request