next-api-analyzer
Version:
Minimal, efficient Next.js API analyzer with Postman-ready testing guides for security, performance, and maintainability
272 lines (206 loc) โข 6.75 kB
Markdown
# Next.js API Route Analyzer
A minimal, efficient analyzer for Next.js API routes focusing on security, performance, and maintainability analysis.
[](https://www.npmjs.com/package/next-api-analyzer)
[](https://opensource.org/licenses/MIT)
## โจ Features
### ๐ฏ Perfect for API Testing
- ๐งช **Postman-Ready Testing Guide** - Test APIs without reading backend code!
- ๐ **Complete Parameter Documentation** - Path params, query params, body params, headers
- ๐ **Auth Requirements** - Know exactly what authentication is needed
- ๐ **Ready-to-Use JSON** - Copy-paste request body structures
- ๐ **Quick Reference Table** - All endpoints at a glance for Postman collections
### ๐ Analysis Capabilities
- **Security Analysis** - Detects 7 vulnerability types (SQL injection, XSS, hardcoded secrets, etc.)
- **Performance Metrics** - Complexity analysis and optimization recommendations
- **Auth Detection** - Identifies 7 authentication methods (JWT, NextAuth.js, Bearer Token, etc.)
- **Smart Route Discovery** - Automatically finds and analyzes App Router & Pages Router
### ๐ Developer Experience
- **Minimal Dependencies** - Only 4 runtime packages for fast installation
- **Clear Reports** - Markdown & JSON formats
- **Actionable Recommendations** - Get specific guidance to improve your APIs
- **CI/CD Ready** - JSON output for automation
## ๐ Installation
```bash
npm install --save-dev next-api-analyzer
# or
yarn add --dev next-api-analyzer
# or
pnpm add -D next-api-analyzer
```
## ๐ Quick Start
### CLI Usage
```bash
# Analyze your API routes
npx next-api-analyzer analyze
# Analyze specific directory
npx next-api-analyzer analyze --dir src/app/api
# Output as JSON
npx next-api-analyzer analyze --json
# Security-focused analysis
npx next-api-analyzer analyze --security
# Performance-focused analysis
npx next-api-analyzer analyze --performance
# Initialize configuration file
npx next-api-analyzer init
```
### Programmatic Usage
```typescript
import { NextApiAnalyzer } from 'next-api-analyzer'
const analyzer = new NextApiAnalyzer({
apiDir: 'src/app/api',
outputDir: './reports'
})
const analysis = await analyzer.analyzeRoutes()
const report = analyzer.generateReport(analysis)
console.log(`Security Score: ${analysis.summary.securityScore}%`)
console.log(`Performance Score: ${analysis.summary.performanceScore}%`)
console.log(`Recommendations: ${analysis.recommendations.length}`)
```
## ๐ Configuration
Create a `api-analyzer.config.json` file:
```json
{
"apiDir": "src/app/api",
"outputDir": "./api-analysis",
"enableSecurityAnalysis": true,
"enablePerformanceAnalysis": true,
"thresholds": {
"security": 80,
"performance": 70,
"maintainability": 75,
"complexity": 10
}
}
```
## ๐งช Perfect for API Testers
### What You Get for Each Endpoint:
โ
**Authentication Status** - ๐ Required or ๐ Public
โ
**Auth Type** - JWT, Bearer Token, NextAuth.js, etc.
โ
**Required Headers** - `authorization`, `content-type`, etc.
โ
**Path Parameters** - Dynamic route segments with types
โ
**Query Parameters** - URL query strings with types
โ
**Request Body** - JSON structure ready to copy-paste
โ
**Response Codes** - All possible HTTP status codes
โ
**Security Features** - Rate limiting, CORS, validation
โ
**Risk Level** - Know which endpoints need extra testing
### Example Output:
```markdown
### POST /api/users/:id
๐ Authentication Required: Yes
Auth Type: JWT, Bearer Token
Required Headers:
- authorization
- content-type
Path Parameters:
- id (string, required)
Request Body:
{
"name": "<string>",
"email": "<string>"
}
Expected Response Codes: 200, 400, 401, 404
Risk Level: MEDIUM | Complexity: 8
```
## ๐ What It Analyzes
### Security (7 Vulnerability Types)
- SQL injection patterns
- XSS vulnerabilities
- Hardcoded secrets
- Weak cryptography
- CORS misconfigurations
- Path traversal
- Command injection
### Authentication (7 Methods Detected)
- NextAuth.js
- JWT tokens
- Bearer Token
- API Key
- Session-based
- Firebase Auth
- Supabase Auth
### Performance
- Cyclomatic complexity
- Code size metrics
- Blocking operations
- Dependencies analysis
### API Information
- HTTP methods
- Parameters (path, query, body)
- Headers accessed
- Response status codes
- Middleware usage
## ๐ Report Sections
Generated reports include:
1. **๐ Summary** - Overall metrics and scores
2. **๐ฏ Risk Distribution** - Count by risk level
3. **๐ HTTP Methods Breakdown** - API surface area
4. **๐ก Recommendations** - Security and performance issues
5. **๐งช API Testing Guide** - Detailed endpoint documentation โญ
6. **๐ Quick Reference Table** - All endpoints at a glance โญ
## ๐ง API
### NextApiAnalyzer
```typescript
class NextApiAnalyzer {
constructor(config?: Partial<AnalyzerConfig>)
async analyzeRoutes(): Promise<ApiAnalysisResult>
generateReport(analysis: ApiAnalysisResult): string
}
```
### Configuration Types
```typescript
interface AnalyzerConfig {
apiDir: string
outputDir: string
includePatterns: string[]
excludePatterns: string[]
enablePerformanceAnalysis: boolean
enableSecurityAnalysis: boolean
thresholds: {
security: number
performance: number
maintainability: number
complexity: number
}
}
```
## ๐ป Development
```bash
# Install dependencies
npm install
# Build
npm run build
# Dev mode
npm run dev
```
## ๐ฆ Package Stats
- **Total Source Code**: ~1,400 lines
- **Runtime Dependencies**: 4 packages
- **Dev Dependencies**: 2 packages
- **Build Output**: ~24 KB (minified)
- **Installation Time**: ~15 seconds
## ๐ฏ Use Cases
### For QA/Testers:
โ
Test APIs without backend access
โ
Create Postman Collections quickly
โ
Prioritize testing by risk level
โ
Write comprehensive test cases
### For Developers:
โ
Auto-generated API documentation
โ
Security vulnerability detection
โ
Code complexity analysis
โ
Refactoring guidance
### For DevOps/CI/CD:
โ
Automated quality checks
โ
JSON output for scripting
โ
Enforce security standards
โ
Documentation pipeline
## ๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## ๐ License
MIT ยฉ [Pranshu Patel](https://github.com/pranshu05)
## ๐ Links
- [GitHub Repository](https://github.com/pranshu05/next-api-analyzer)
- [npm Package](https://www.npmjs.com/package/next-api-analyzer)
- [Issues](https://github.com/pranshu05/next-api-analyzer/issues)
---
**Made with โค๏ธ for the Next.js community**