Skip to content

minaa66/nextjs-analyzer-1.0.0

Repository files navigation

nextjs-analyzer

A powerful library to analyze Next.js applications, generate documentation, and perform security analysis. Designed to be clean, scalable, and extensible for public use.

License: MIT

Features

  • 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

Installation

Option 1: Clone and Build

# 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 link

Now you can use the CLI anywhere:

nextjs-analyzer /path/to/your/nextjs-app

Option 2: Download Release

  1. Download the latest release from the releases page
  2. Extract the archive
  3. Follow the build steps above

Quick Start

CLI Usage

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-security

CLI Options

Usage: 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

Example Output

Routes Discovered

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 |

Security Findings

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

Programmatic Usage

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 };
}

Configuration

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',
};

Security Rules

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

Plugin Development

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.js

CI/CD Integration

GitHub Actions

name: 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.json

Exit Codes

  • 0: Analysis completed with no issues above the threshold
  • 1: Issues found at or above the specified threshold level

Supported Next.js Features

  • Pages Router (pages/)
  • App Router (app/)
  • API Routes (both routers)
  • Dynamic routes ([id], [...slug], [[...optional]])
  • Middleware
  • Data fetching methods (getServerSideProps, getStaticProps, etc.)
  • next.config.js parsing

Development

# 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 format

Project Structure

nextjs-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

License

MIT

Contributing

Contributions are welcome! Please read our contributing guidelines before submitting a pull request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors