npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

route-extractor

v1.0.8

Published

Extract routes from React projects supporting Next.js, Vite, and React Router DOM

Readme

Route Extractor

A powerful library to extract routes from React projects supporting multiple frameworks including Next.js, Vite, and React Router DOM.

Features

  • Multi-Framework Support: Automatically detects and extracts routes from:
    • Next.js (App Router & Pages Router)
    • Vite + React Router DOM
    • React Router DOM standalone
  • Smart Detection: Automatically identifies the framework being used
  • Comprehensive Route Parsing: Extracts dynamic routes, catch-all routes, and nested routes
  • Babel AST Traversal: Uses advanced parsing for React Router DOM projects
  • TypeScript Support: Full TypeScript definitions included
  • CLI Tool: Command-line interface for easy integration

Installation

bun add route-extractor

Usage

Command Line Interface (CLI)

The library includes a CLI tool that you can use directly from the command line:

# Basic usage
route-extractor ./my-react-project

# Output in JSON format
route-extractor ./my-react-project --json

# Show help
route-extractor --help

# Show version
route-extractor --version

CLI Options

  • --json: Output results in JSON format
  • --pretty: Pretty print the results (default)
  • --help, -h: Show help message
  • --version, -v: Show version information

CLI Examples

# Analyze current directory
route-extractor .

# Analyze specific project
route-extractor /path/to/nextjs-app

# Get JSON output for scripting
route-extractor ./my-app --json > routes.json

Programmatic Usage

import { extractSiteRoutes } from "route-extractor";

// Extract routes from a React project
const result = await extractSiteRoutes("/path/to/your/react/project");

console.log("Framework:", result.framework.name);
console.log("Routes:", result.routes);
console.log("Errors:", result.errors);

Example Output

{
  framework: { name: "nextjs", version: "14.0.0" },
  routes: [
    {
      path: "/",
      component: "index.tsx",
      dynamic: false,
      catchAll: false
    },
    {
      path: "/users/:id",
      component: "users/[id]/page.tsx",
      dynamic: true,
      catchAll: false
    },
    {
      path: "/blog/*",
      component: "blog/[...slug]/page.tsx",
      dynamic: true,
      catchAll: true
    }
  ],
  errors: []
}

Supported Frameworks

Next.js

App Router (Next.js 13+)

  • Detects app/ directory
  • Parses page.tsx, layout.tsx, loading.tsx, error.tsx, not-found.tsx
  • Supports dynamic routes [id] and catch-all routes [...slug]

Pages Router

  • Detects pages/ directory
  • Converts file paths to route paths
  • Supports dynamic and catch-all routes

Vite + React Router DOM

  • Scans for React Router usage in project files
  • Uses Babel AST traversal to parse route definitions
  • Supports both JSX <Route> elements and createBrowserRouter configuration

React Router DOM

  • Comprehensive parsing of React Router configurations
  • AST-based analysis for accurate route extraction
  • Supports nested routes and complex configurations

API Reference

extractSiteRoutes(projectPath: string): Promise<ExtractionResult>

The main function that extracts routes from a React project.

Parameters:

  • projectPath (string): Absolute or relative path to the React project directory

Returns:

  • Promise<ExtractionResult>: Object containing framework info, routes, and any errors

Types

interface RouteInfo {
  path: string; // The route path (e.g., '/users/:id')
  component?: string; // Component file path (if available)
  children?: RouteInfo[]; // Nested routes
  dynamic?: boolean; // Whether the route is dynamic
  catchAll?: boolean; // Whether the route is a catch-all route
}

interface FrameworkInfo {
  name: "nextjs" | "vite" | "react-router-dom" | "unknown";
  version?: string;
}

interface ExtractionResult {
  framework: FrameworkInfo;
  routes: RouteInfo[];
  errors: string[];
}

Examples

Next.js Project

import { extractSiteRoutes } from "route-extractor";

const result = await extractSiteRoutes("./my-nextjs-app");

if (result.framework.name === "nextjs") {
  console.log("Next.js routes found:");
  result.routes.forEach((route) => {
    console.log(`${route.path} -> ${route.component}`);
  });
}

React Router DOM Project

import { extractSiteRoutes } from "route-extractor";

const result = await extractSiteRoutes("./my-react-app");

if (result.framework.name === "react-router-dom") {
  console.log("React Router routes found:");
  result.routes.forEach((route) => {
    console.log(`Route: ${route.path}`);
    if (route.children) {
      route.children.forEach((child) => {
        console.log(`  └─ ${child.path}`);
      });
    }
  });
}

CLI Integration

#!/bin/bash
# Extract routes and save to file
route-extractor ./my-app --json > routes.json

# Process routes in a script
ROUTES=$(route-extractor ./my-app --json)
echo "Found $(echo $ROUTES | jq '.routes | length') routes"

Error Handling

The library provides comprehensive error handling:

const result = await extractSiteRoutes("./invalid-path");

if (result.errors.length > 0) {
  console.error("Extraction errors:");
  result.errors.forEach((error) => console.error(`- ${error}`));
}

Common errors include:

  • Project path does not exist
  • Unsupported framework
  • File parsing errors
  • Missing dependencies

Development

Building

bun run build

Development Mode

bun run dev

Testing

bun test

CLI Development

# Make CLI executable
chmod +x bin/cli.js

# Test CLI locally
bun run bin/cli.js --help

Dependencies

  • @babel/parser - JavaScript/TypeScript parsing
  • @babel/traverse - AST traversal
  • @babel/types - AST type definitions
  • glob - File pattern matching
  • fs-extra - Enhanced file system operations

License

MIT