UNPKG

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
# Next.js API Route Analyzer A minimal, efficient analyzer for Next.js API routes focusing on security, performance, and maintainability analysis. [![npm version](https://badge.fury.io/js/next-api-analyzer.svg)](https://www.npmjs.com/package/next-api-analyzer) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](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**