### Example AI Prompt Output Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md This is an example of the structured output format for AI prompts, indicating a specific Vercel optimization issue. ```json { "vercel-doctor/vercel-no-force-dynamic::src/app/page.tsx:15:1": "Fix this Vercel optimization issue..." } ``` -------------------------------- ### Full Vercel Doctor Configuration Example Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/configuration.mdx This example demonstrates a comprehensive configuration including ignored rules and files, feature toggles, and diff mode settings. ```json { "ignore": { "rules": [ "vercel-doctor/vercel-consider-bun-runtime", "vercel-doctor/vercel-avoid-platform-cron" ], "files": ["src/generated/**", "e2e/**"] }, "lint": true, "deadCode": true, "verbose": false, "diff": "main" } ``` -------------------------------- ### Example AI Prompt Output for Vercel Optimization Source: https://context7.com/aniket-508/vercel-doctor/llms.txt An example of the JSON output generated by Vercel Doctor for AI tools, detailing a specific optimization issue and its fix strategy. ```json { "vercel-doctor/async-parallel::src/app/page.tsx:15:1": "Fix this Vercel optimization issue:\n\n**Rule:** async-parallel\n**File:** src/app/page.tsx:15:1\n**Severity:** warning\n**Issue:** Sequential awaits detected\n\n**Fix Strategy:**\nRun independent async operations in parallel to reduce total execution time\n\n**Example:**\n```\n// Before:\nconst a = await fetchA();\nconst b = await fetchB();\n\n// After:\nconst [a, b] = await Promise.all([fetchA(), fetchB()]);\n```" } ``` -------------------------------- ### Vercel Doctor Configuration Example (JSON) Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Configure Vercel Doctor by creating a vercel-doctor.config.json file in your project root to ignore specific rules or files. ```json { "ignore": { "rules": ["vercel-doctor/nextjs-image-missing-sizes", "knip/exports"], "files": ["src/generated/**"] } } ``` -------------------------------- ### Vercel Doctor Configuration Example (package.json) Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Alternatively, configure Vercel Doctor using the "vercelDoctor" key within your package.json file. This configuration is overridden by vercel-doctor.config.json if both exist. ```json { "vercelDoctor": { "ignore": { "rules": ["vercel-doctor/nextjs-image-missing-sizes"] } } } ``` -------------------------------- ### Run Vercel Doctor Locally Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Execute the Vercel Doctor CLI locally after cloning and installing dependencies. Replace the path with your project's directory. ```bash node packages/vercel-doctor/dist/cli.js /path/to/your/nextjs-project ``` -------------------------------- ### Install Vercel Doctor Skill for AI Agents Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Installs the Vercel Doctor optimization skill for supported AI coding agents. This is a one-line command for easy integration. ```bash # One-line install for supported AI agents curl -fsSL https://vercel-doctor.com/install-skill.sh | bash ``` -------------------------------- ### Example Score Calculation Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/scoring.mdx Demonstrates the score calculation for a project with 2 error rules and 8 warning rules, resulting in a score of 91. ```plaintext penalty = (2 × 1.5) + (8 × 0.75) = 3 + 6 = 9 score = max(0, round(100 - 9)) = 91 → Great ``` -------------------------------- ### Install Vercel Doctor AI Skill Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/ai-skills.mdx Use this command to install Vercel Doctor as an AI skill. The installer auto-detects and installs for all supported tools on your system. ```bash npx vercel-doctor@latest install-skill ``` ```bash curl -fsSL https://vercel-doctor.com/install-skill.sh | bash ``` -------------------------------- ### Clone Vercel Doctor Repository Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Clone the Vercel Doctor repository from GitHub to contribute to the project. This command initializes the project setup. ```bash git clone https://github.com/Aniket-508/vercel-doctor cd vercel-doctor pnpm install pnpm -r run build ``` -------------------------------- ### Vercel Doctor CLI Usage Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Examples of how to use the Vercel Doctor CLI to generate reports and AI prompts. ```APIDOC ## Vercel Doctor CLI Usage ### Generate Markdown Report This command generates a markdown report of the project's diagnostics. ```bash npx vercel-doctor . --output markdown --report report.md ``` ### Export AI Prompts This command exports AI prompts for fixing issues, compatible with tools like Cursor, Claude, and Windsurf. The output format is determined by the file extension. **Export as JSON (for scripts, automation):** ```bash npx vercel-doctor . --ai-prompts fixes.json ``` **Export as Markdown (for manual copy-paste into AI chats):** ```bash npx vercel-doctor . --ai-prompts fixes.md ``` Each AI prompt includes the rule violation, file location, code examples, and fix instructions. ``` -------------------------------- ### Node.js API - diagnose() Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Programmatically scan a Next.js project and get structured diagnostics. ```APIDOC ## Node.js API - diagnose() ### Description Programmatically scan a Next.js project and get structured diagnostics. ### Method `diagnose(projectPath: string, options?: DiagnoseOptions): Promise` ### Endpoint `import { diagnose } from "vercel-doctor/api";` ### Parameters #### Path Parameter - `projectPath` (string) - Required - The path to the Next.js project directory. #### Options (Optional) - `lint` (boolean) - Enable lint checks (default: `true`). - `deadCode` (boolean) - Enable dead code detection (default: `true`). - `includePaths` (string[]) - Only scan specific files (useful for diff mode). ### Request Example ```javascript import { diagnose } from "vercel-doctor/api"; // Basic usage const result = await diagnose("./path/to/your/nextjs-project"); console.log(result.score); // { score: 82, label: "Good" } or null console.log(result.diagnostics); // Array of Diagnostic objects console.log(result.project); // Detected framework, React version, etc. console.log(result.elapsedMilliseconds); // Scan duration // With options const resultWithOptions = await diagnose(".", { lint: true, deadCode: true, includePaths: [ "src/app/page.tsx", "src/components/Nav.tsx" ] }); // Process diagnostics for (const diagnostic of resultWithOptions.diagnostics) { console.log(`${diagnostic.severity}: ${diagnostic.message}`); console.log(` File: ${diagnostic.filePath}:${diagnostic.line}:${diagnostic.column}`); console.log(` Rule: ${diagnostic.plugin}/${diagnostic.rule}`); console.log(` Help: ${diagnostic.help}`); } ``` ### Response #### Success Response (200) - `diagnostics` (Diagnostic[]) - An array of diagnostic objects detailing issues found. - `score` (ScoreResult | null) - An object containing the project's health score and label, or null if not applicable. - `project` (ProjectInfo) - Information about the detected project configuration. - `elapsedMilliseconds` (number) - The time taken for the scan in milliseconds. ### Diagnostic Interface ```typescript interface Diagnostic { filePath: string; plugin: string; rule: string; severity: "error" | "warning"; message: string; help: string; line: number; column: number; category: string; weight?: number; } ``` ### ScoreResult Interface ```typescript interface ScoreResult { score: number; label: string; } ``` ### ProjectInfo Interface ```typescript interface ProjectInfo { rootDirectory: string; projectName: string; reactVersion: string | null; framework: "nextjs" | "vite" | "cra" | "remix" | "gatsby" | "unknown"; nextVersion: string | null; nextMajorVersion: number | null; hasTypeScript: boolean; sourceFileCount: number; } ``` ``` -------------------------------- ### Get Diff Info and Filter Source Files Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Use `getDiffInfo` to retrieve changed files for CI/CD diff-mode scanning. `filterSourceFiles` can then be used to narrow down the list to JavaScript/TypeScript files. ```javascript import { getDiffInfo, filterSourceFiles } from "vercel-doctor/api"; // Get diff information for current branch const diffInfo = getDiffInfo("./project-root"); // diffInfo: { currentBranch, baseBranch, changedFiles, isCurrentChanges } // Get diff info with explicit base branch const diffInfo = getDiffInfo("./project-root", "main"); if (diffInfo) { console.log(`Branch: ${diffInfo.currentBranch} vs ${diffInfo.baseBranch}`); console.log(`Changed files: ${diffInfo.changedFiles.length}`); // Filter to only source files (JS/TS/TSX/JSX) const sourceFiles = filterSourceFiles(diffInfo.changedFiles); console.log(`Source files to scan: ${sourceFiles.length}`); } ``` -------------------------------- ### Install Vercel Doctor Coding Agent Skill Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Install Vercel Doctor as a skill for your coding agent using this curl command. ```bash curl -fsSL https://vercel-doctor.com/install-skill.sh | bash ``` -------------------------------- ### Ensure Explicit Cache Policy for GET Handlers Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/caching.mdx GET route handlers without explicit cache configuration (e.g., `Cache-Control` headers, `revalidate` export, `dynamic` export) may miss CDN caching opportunities. Define a cache policy to ensure optimal performance. ```typescript export async function GET() { const data = await fetchData(); return Response.json(data); } ``` ```typescript export const revalidate = 3600; export async function GET() { const data = await fetchData(); return Response.json(data); } ``` -------------------------------- ### Get Project Score via API Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/scoring.mdx Use this curl command to programmatically calculate a project's score by sending a JSON payload containing diagnostics to the /api/score endpoint. ```bash curl -X POST https://www.vercel-doctor.com/api/score \ -H "Content-Type: application/json" \ -d '{"diagnostics": [...]}' ``` -------------------------------- ### Deploy with Archive Mode for Large Projects Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/platform.mdx Use the `--archive=tgz` flag with `vercel deploy` for projects with many files (5,000+). This uploads a single tarball, reducing deployment time by approximately 50%. ```bash vercel deploy --archive=tgz ``` -------------------------------- ### Run Basic Vercel Doctor Scan Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Execute a basic scan of the current Next.js project directory. Use the --verbose flag for detailed output including file paths and line numbers. Specify a directory to scan a different project. ```bash npx -y vercel-doctor@latest . ``` ```bash npx -y vercel-doctor@latest . --verbose ``` ```bash npx -y vercel-doctor@latest /path/to/nextjs-project ``` -------------------------------- ### Use Archive Deployments for Large Projects Source: https://context7.com/aniket-508/vercel-doctor/llms.txt For large Next.js projects, consider using the `vercel deploy --archive=tgz` command to create an archive deployment, which can improve deployment performance and reliability. ```bash // Rule: vercel-suggest-deploy-archive // Suggests archive deployment for large projects // Command line vercel deploy --archive=tgz ``` -------------------------------- ### Avoid Side Effects in GET Handlers Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/caching.mdx GET route handlers should not mutate cookies, headers, or databases. Use POST or other appropriate HTTP methods for mutations. This prevents CSRF vulnerabilities and enables caching. ```typescript export async function GET() { cookies().delete("session"); return Response.json({ ok: true }); } ``` ```typescript export async function POST() { cookies().delete("session"); return Response.json({ ok: true }); } ``` -------------------------------- ### Prevent Side Effects in Next.js GET Handlers Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Avoid performing mutations within GET request handlers in Next.js API routes to prevent Cross-Site Request Forgery (CSRF) risks. Use POST requests for mutations. ```typescript // Rule: nextjs-no-side-effect-in-get-handler // Detects mutations in GET handlers (CSRF risk) // Before (mutation in GET - vulnerable) export async function GET() { await db.users.update({ lastSeen: new Date() }); return Response.json({ ok: true }); } // After (use POST for mutations) export async function POST() { await db.users.update({ lastSeen: new Date() }); return Response.json({ ok: true }); } ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Run Vercel Doctor on a specified directory. Defaults to the current directory if none is provided. ```bash npx -y vercel-doctor@latest [directory] [options] ``` -------------------------------- ### Enable Turbopack Cache for Next.js Builds Source: https://context7.com/aniket-508/vercel-doctor/llms.txt For Next.js 16 and above, enable the `turbopackFileSystemCacheForBuild` experimental option in `next.config.js` to leverage Turbopack's cache for faster builds. ```javascript // Rule: vercel-suggest-turbopack-build-cache // Suggests enabling Turbopack cache for Next.js 16+ // next.config.js module.exports = { experimental: { turbopackFileSystemCacheForBuild: true } }; ``` -------------------------------- ### Run E2E Tests Source: https://github.com/aniket-508/vercel-doctor/blob/main/AGENTS.md Execute end-to-end tests for the project. Ensure all tests pass before committing. ```bash pnpm test ``` -------------------------------- ### Enable Turbopack Build Cache in Next.js Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/platform.mdx Configure `turbopackFileSystemCacheForBuild` in `next.config.js` for Next.js 16+ projects to significantly reduce build times. ```javascript // next.config.js module.exports = { experimental: { turbopackFileSystemCacheForBuild: true, }, }; ``` -------------------------------- ### Run Vercel Doctor CLI Source: https://github.com/aniket-508/vercel-doctor/blob/main/skills/vercel-doctor/SKILL.md Execute the Vercel Doctor CLI to scan your project. Use the --verbose flag for detailed output and --diff to compare against previous runs. ```bash npx -y vercel-doctor@latest . --verbose --diff ``` -------------------------------- ### Run Linter Source: https://github.com/aniket-508/vercel-doctor/blob/main/AGENTS.md Apply linting rules to maintain code quality and consistency. Run this command regularly. ```bash pnpm lint ``` -------------------------------- ### Scan Multiple Workspace Projects Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Scans multiple specified projects within a workspace, separated by commas. ```bash npx -y vercel-doctor@latest . --project web,api ``` -------------------------------- ### Configure Remote Image Patterns in Next.js Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Instead of globally disabling image optimization, configure `remotePatterns` in `next.config.js` to specify allowed image hostnames for optimization. ```javascript // Rule: vercel-image-global-unoptimized // Detects globally disabled image optimization in next.config.js // Before (all images unoptimized) module.exports = { images: { unoptimized: true } }; // After (specific remote patterns) module.exports = { images: { remotePatterns: [ { hostname: "cdn.example.com" } ] } }; ``` -------------------------------- ### Generate Markdown Report Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/reports.mdx Use this command to generate a markdown report of project issues. Specify the output file with the `--report` flag. ```bash npx vercel-doctor . --output markdown --report report.md ``` -------------------------------- ### CLI Usage - Output Formats Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Generate reports in different formats for various use cases. ```APIDOC ## CLI Usage - Output Formats ### Description Generate reports in different formats for various use cases. ### Method CLI Command ### Endpoint `npx vercel-doctor . --output [format] [--report [file]] [--ai-prompts [file]]` ### Parameters #### CLI Flags - `--output [format]` (string) - Required - Specify the output format. Supported formats: `human` (default), `json`, `markdown`. - `--report [file]` (string) - Optional - Write the human-readable report to the specified file. - `--ai-prompts [file]` (string) - Optional - Export AI fix prompts to the specified file. Can be `.json` or `.md`. ### Request Example ```bash # Human-readable terminal output (default) npx vercel-doctor . --output human # JSON output for programmatic processing npx vercel-doctor . --output json # Markdown output npx vercel-doctor . --output markdown # Write human-readable report to file npx vercel-doctor . --output markdown --report report.md # Export AI fix prompts as JSON (for automation) npx vercel-doctor . --ai-prompts fixes.json # Export AI fix prompts as Markdown (for copy-paste into AI tools) npx vercel-doctor . --ai-prompts fixes.md ``` ``` -------------------------------- ### Run Code Formatter Source: https://github.com/aniket-508/vercel-doctor/blob/main/AGENTS.md Format code according to project standards. This ensures consistent code style across the codebase. ```bash pnpm format ``` -------------------------------- ### CLI Usage - Scan Options Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Configure scan behavior with CLI flags. ```APIDOC ## CLI Usage - Scan Options ### Description Configure scan behavior with CLI flags. ### Method CLI Command ### Endpoint `npx vercel-doctor . [FLAGS]` ### Parameters #### CLI Flags - `--no-lint` (boolean) - Optional - Skip linting (only run dead code detection). - `--no-dead-code` (boolean) - Optional - Skip dead code detection (only run linting). - `--score` (boolean) - Optional - Output only the score (for CI/CD). - `--yes` (boolean) - Optional - Skip prompts, auto-select all workspace projects. - `--diff` (boolean) - Optional - Scan only files changed vs base branch. - `--diff [branch]` (string) - Optional - Scan only files changed vs specified base branch. - `--project [project-name]` (string) - Optional - Select specific workspace project(s). - `--project "[project-a],[project-b]"` (string) - Optional - Select multiple specific workspace projects. - `--offline` (boolean) - Optional - Run offline (skip telemetry). ### Request Example ```bash # Skip linting (only run dead code detection) npx vercel-doctor . --no-lint # Skip dead code detection (only run linting) npx vercel-doctor . --no-dead-code # Output only the score (for CI/CD) npx vercel-doctor . --score # Skip prompts, auto-select all workspace projects npx vercel-doctor . --yes # Scan only files changed vs base branch npx vercel-doctor . --diff npx vercel-doctor . --diff main # Select specific workspace project(s) npx vercel-doctor . --project my-app npx vercel-doctor . --project "app-a,app-b" # Run offline (skip telemetry) npx vercel-doctor . --offline ``` ``` -------------------------------- ### Parallelize Sequential Database Calls with Promise.all Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/platform.mdx Use `Promise.all` to execute independent database queries in parallel. This reduces latency compared to sequential awaits, especially when dealing with 3 or more queries. ```typescript const users = await prisma.user.findMany(); const posts = await prisma.post.findMany(); const tags = await prisma.tag.findMany(); ``` ```typescript const [users, posts, tags] = await Promise.all([ prisma.user.findMany(), prisma.post.findMany(), prisma.tag.findMany(), ]); ``` -------------------------------- ### CLI Usage - Basic Scan Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Run Vercel Doctor on a Next.js project to detect billing optimization issues. ```APIDOC ## CLI Usage - Basic Scan ### Description Run Vercel Doctor on a Next.js project to detect billing optimization issues. ### Method CLI Command ### Endpoint `npx -y vercel-doctor@latest .` ### Parameters #### CLI Flags - `--verbose` (boolean) - Optional - Show verbose output with file details and line numbers. - `/path/to/nextjs-project` (string) - Optional - Specify a directory to scan. ### Request Example ```bash # Basic scan of current directory npx -y vercel-doctor@latest . # Verbose output with file details and line numbers npx -y vercel-doctor@latest . --verbose # Scan specific directory npx -y vercel-doctor@latest /path/to/nextjs-project ``` ``` -------------------------------- ### Optimize Next.js Image Component with Sizes Prop Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Use the `sizes` prop on the Next.js Image component to enable responsive image sizing and prevent unnecessary downloads of all image sizes. ```typescript // Rule: nextjs-image-missing-sizes // Detects Image components without sizes prop // Before (downloads all sizes) Hero // After (responsive sizing) Hero ``` -------------------------------- ### Configure Diagnose Function Options Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md The `diagnose` function accepts an optional second argument to configure specific checks like linting and dead code detection. ```javascript const result = await diagnose(".", { lint: true, // run lint checks (default: true) deadCode: true, // run dead code detection (default: true) }); ``` -------------------------------- ### Enable Fetch Caching with Revalidation Source: https://context7.com/aniket-508/vercel-doctor/llms.txt This rule identifies `fetch` calls with `cache: "no-store"` and recommends using `cache: "force-cache"` with `next: { revalidate: ... }` to enable caching. ```typescript // Rule: vercel-no-no-store-fetch // Detects fetch calls that disable caching // Before (never cached) const data = await fetch(url, { cache: "no-store" }); // After (cached with revalidation) const data = await fetch(url, { cache: "force-cache", next: { revalidate: 3600 } }); ``` -------------------------------- ### Vercel Doctor Configuration (JSON) Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Configure Vercel Doctor by creating a `vercel-doctor.config.json` file at your project root. This allows customization of ignored rules and files, and enables/disables linting and dead code detection. ```json { "ignore": { "rules": [ "vercel-doctor/nextjs-image-missing-sizes", "knip/exports", "vercel-doctor/async-parallel" ], "files": [ "src/generated/**", "**/*.test.tsx", "**/__mocks__/**" ] }, "lint": true, "deadCode": true, "verbose": false, "diff": false } ``` -------------------------------- ### Configuration Options Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Details on the configuration options available for Vercel Doctor. ```APIDOC ## Configuration Options These options can be configured, and CLI flags always override config values. | Key | Type | Default | Description | | -------------- | ------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `ignore.rules` | `string[]` | `[]` | Rules to suppress, using the `plugin/rule` format shown in diagnostic output (e.g. `vercel-doctor/async-parallel`, `knip/exports`) | | `ignore.files` | `string[]` | `[]` | File paths to exclude, supports glob patterns (`src/generated/**`, `**/*.test.tsx`) | | `lint` | `boolean` | `true` | Enable/disable lint checks (same as `--no-lint`) | | `deadCode` | `boolean` | `true` | Enable/disable dead code detection (same as `--no-dead-code`) | | `verbose` | `boolean` | `false` | Show file details per rule (same as `--verbose`) | | `diff` | `boolean | string` | — | Force diff mode (`true`) or pin a base branch (`"main"`). Set to `false` to disable auto-detection. | ``` -------------------------------- ### Export AI Fix Prompts Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/reports.mdx Use the `--ai-prompts` flag to export AI-compatible prompts for fixing identified issues. The output format is auto-detected by the file extension. ```bash npx vercel-doctor . --ai-prompts fixes.json ``` ```bash npx vercel-doctor . --ai-prompts fixes.md ``` -------------------------------- ### Basic Vercel Doctor Configuration Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/configuration.mdx Use this JSON structure in `vercel-doctor.config.json` to specify rules and files to ignore. ```json { "ignore": { "rules": ["vercel-doctor/nextjs-link-prefetch-default"], "files": ["src/generated/**"] } } ``` -------------------------------- ### Scan Current Directory Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Initiates a scan of the current directory to identify potential issues. ```bash npx -y vercel-doctor@latest . ``` -------------------------------- ### Consider ISR for `getStaticProps` Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/caching.mdx Pages using `getStaticProps` without a `revalidate` value are built at deploy time. Implementing Incremental Static Regeneration (ISR) with `revalidate` allows on-demand generation and caching, which is beneficial for large sites. ```typescript export async function getStaticProps() { const data = await fetchData(); return { props: { data }, revalidate: 3600, }; } ``` -------------------------------- ### Configure Vercel Doctor Scan Options Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Control the scan behavior using CLI flags. Options include skipping linting or dead code detection, outputting only the score, automatically selecting workspace projects, scanning only changed files, selecting specific projects, and running offline. ```bash npx vercel-doctor . --no-lint ``` ```bash npx vercel-doctor . --no-dead-code ``` ```bash npx vercel-doctor . --score ``` ```bash npx vercel-doctor . --yes ``` ```bash npx vercel-doctor . --diff ``` ```bash npx vercel-doctor . --diff main ``` ```bash npx vercel-doctor . --project my-app ``` ```bash npx vercel-doctor . --project "app-a,app-b" ``` ```bash npx vercel-doctor . --offline ``` -------------------------------- ### Scan Specific Workspace Project Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Targets a specific project within a workspace for scanning. ```bash npx -y vercel-doctor@latest . --project web ``` -------------------------------- ### Package.json Vercel Doctor Configuration Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/configuration.mdx Alternatively, configure Vercel Doctor by adding a `vercelDoctor` key to your `package.json` file. ```json { "vercelDoctor": { "ignore": { "rules": ["knip/exports"], "files": ["src/generated/**"] } } } ``` -------------------------------- ### Node.js API Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Programmatic usage of the Vercel Doctor library using the `diagnose` function. ```APIDOC ## Node.js API You can use Vercel Doctor programmatically with the `diagnose` function. ### Basic Usage ```js import { diagnose } from "vercel-doctor/api"; const result = await diagnose("./path/to/your/nextjs-project"); console.log(result.score); // { score: 82, label: "Good" } or null console.log(result.diagnostics); // Array of Diagnostic objects console.log(result.project); // Detected framework, React version, etc. ``` ### With Options The `diagnose` function accepts an optional second argument for configuration. ```js const result = await diagnose(".", { lint: true, // run lint checks (default: true) deadCode: true, // run dead code detection (default: true) }); ``` ### Diagnostic Object Structure Each diagnostic object has the following shape: ```ts interface Diagnostic { filePath: string; plugin: string; rule: string; severity: "error" | "warning"; message: string; help: string; line: number; column: number; category: string; } ``` ``` -------------------------------- ### Vercel Doctor Configuration (package.json) Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Alternatively, embed Vercel Doctor configuration within your `package.json` file. This provides the same customization options as the separate JSON configuration file. ```json { "name": "my-nextjs-app", "version": "1.0.0", "vercelDoctor": { "ignore": { "rules": ["vercel-doctor/nextjs-image-missing-sizes"], "files": ["src/generated/**"] }, "lint": true, "deadCode": true, "verbose": false } } ``` -------------------------------- ### Scan with Verbose Output Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Performs a scan and displays file paths and line numbers for each detected rule, providing detailed diagnostic information. ```bash npx -y vercel-doctor@latest . --verbose ``` -------------------------------- ### Disable Default Link Prefetching - Next.js Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/invocations.mdx Detects `` components without `prefetch={false}`. Disabling prefetch globally and adding it back only to critical navigation links can reduce server requests. ```tsx Dashboard Settings Profile ``` ```tsx Dashboard Settings Profile ``` -------------------------------- ### Diagnose Project with Node.js API Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Use the `diagnose` function from the Vercel Doctor API to programmatically analyze a Next.js project. It returns a result object containing the project score, diagnostics, and detected framework details. ```javascript import { diagnose } from "vercel-doctor/api"; const result = await diagnose("./path/to/your/nextjs-project"); console.log(result.score); // { score: 82, label: "Good" } or null console.log(result.diagnostics); // Array of Diagnostic objects console.log(result.project); // Detected framework, React version, etc. ``` -------------------------------- ### Programmatic API Import Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Imports the 'run' function from the Vercel Doctor programmatic API for custom integrations. ```typescript import { run } from "vercel-doctor/api"; ``` -------------------------------- ### Defer Logging and Analytics in Server Actions Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/function-duration.mdx Detects logging or analytics calls within server actions that block the response. Wrapping these calls in `after()` allows the response to finish immediately while the background work continues. ```typescript "use server"; export const updateUser = async (data: FormData) => { await db.user.update({ ... }); console.log("User updated"); analytics.track("user_updated"); }; ``` ```typescript "use server"; import { after } from "next/server"; export const updateUser = async (data: FormData) => { await db.user.update({ ... }); after(() => { console.log("User updated"); analytics.track("user_updated"); }); }; ``` -------------------------------- ### Fetch Server Data in Next.js Server Components Source: https://context7.com/aniket-508/vercel-doctor/llms.txt For data that is required for rendering, fetch it directly within Next.js Server Components instead of using `useEffect` in Client Components to avoid unnecessary client-side fetching. ```typescript // Rule: nextjs-no-client-fetch-for-server-data // Detects client-side fetching that should be server-side // Before (client component with useEffect fetch) "use client"; export function UserProfile({ id }) { const [user, setUser] = useState(null); useEffect(() => { fetch(`/api/users/${id}`).then(r => r.json()).then(setUser); }, [id]); return
{user?.name}
; } // After (server component with direct fetch) export async function UserProfile({ id }) { const user = await fetch(`/api/users/${id}`).then(r => r.json()); return
{user.name}
; } ``` -------------------------------- ### Contributing to Vercel Doctor Source: https://github.com/aniket-508/vercel-doctor/blob/main/README.md Instructions for contributing to the Vercel Doctor project. ```APIDOC ## Contributing To contribute to Vercel Doctor, follow these steps: 1. **Clone the repository:** ```bash git clone https://github.com/Aniket-508/vercel-doctor cd vercel-doctor ``` 2. **Install dependencies:** ```bash pnpm install ``` 3. **Build the project:** ```bash pnpm -r run build ``` 4. **Run locally:** ```bash node packages/vercel-doctor/dist/cli.js /path/to/your/nextjs-project ``` Submit a Pull Request (PR) to contribute your changes. ``` -------------------------------- ### Disable Global Image Optimization Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/image-optimization.mdx Detects `images.unoptimized: true` in `next.config.js`. This disables Vercel Image Optimization globally, leading to increased bandwidth costs and reduced performance. ```javascript // next.config.js module.exports = { images: { unoptimized: true, }, }; ``` ```javascript // next.config.js module.exports = { images: { remotePatterns: [{ hostname: "cdn.example.com" }], }, }; ``` -------------------------------- ### Integrate Vercel Doctor into GitHub Actions Source: https://context7.com/aniket-508/vercel-doctor/llms.txt This YAML configuration sets up a GitHub Actions workflow to automatically run Vercel Doctor on pull requests and pushes to the main branch, performing full or diff scans and checking the score. ```yaml # .github/workflows/vercel-doctor.yml name: Vercel Doctor on: pull_request: branches: [main] push: branches: [main] jobs: scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 # Required for diff mode - uses: actions/setup-node@v4 with: node-version: 20 - name: Install dependencies run: npm ci # Full scan on main branch - name: Run Vercel Doctor (full scan) if: github.ref == 'refs/heads/main' run: npx vercel-doctor . --yes --output json > report.json # Diff scan on pull requests - name: Run Vercel Doctor (diff scan) if: github.event_name == 'pull_request' run: npx vercel-doctor . --yes --diff main --output json > report.json # Fail if score is below threshold - name: Check score run: | SCORE=$(npx vercel-doctor . --score --offline) echo "Score: $SCORE" if [ "$SCORE" -lt 70 ]; then echo "Score below threshold (70)" exit 1 fi ``` -------------------------------- ### Ignoring Files with Glob Patterns Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/configuration.mdx Use glob patterns in the `ignore.files` array to exclude specific files or directories from Vercel Doctor scans. ```json { "ignore": { "files": ["src/generated/**", "**/*.stories.tsx", "scripts/**"] } } ``` -------------------------------- ### CI Usage for Score Output Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Optimized for CI environments, this command skips interactive prompts and outputs only the numeric score. ```bash npx -y vercel-doctor@latest . --yes --score ``` -------------------------------- ### Oxlint Plugin Import Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/cli.mdx Imports the standalone Oxlint plugin for Vercel Doctor's billing lint rules. ```typescript import plugin from "vercel-doctor/oxlint-plugin"; ``` -------------------------------- ### Generate Vercel Doctor Reports in Different Formats Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Customize the output format of Vercel Doctor reports. Supported formats include human-readable terminal output, JSON for programmatic processing, and Markdown. Reports can also be written to a file, and AI fix prompts can be exported. ```bash npx vercel-doctor . --output human ``` ```bash npx vercel-doctor . --output json ``` ```bash npx vercel-doctor . --output markdown ``` ```bash npx vercel-doctor . --output markdown --report report.md ``` ```bash npx vercel-doctor . --ai-prompts fixes.json ``` ```bash npx vercel-doctor . --ai-prompts fixes.md ``` -------------------------------- ### Non-blocking Server Response with next/server after() Source: https://context7.com/aniket-508/vercel-doctor/llms.txt This rule identifies blocking calls in server-side code that should be deferred using `next/server`'s `after()` function to avoid delaying the response. ```typescript // Rule: server-after-nonblocking // Detects blocking calls that should use next/server after() // Before (blocks response) export async function POST(request: Request) { const data = await request.json(); await saveToDatabase(data); analytics.track("form_submitted"); // Blocks response return Response.json({ success: true }); } // After (non-blocking) import { after } from "next/server"; export async function POST(request: Request) { const data = await request.json(); await saveToDatabase(data); after(() => analytics.track("form_submitted")); // Runs after response return Response.json({ success: true }); } ``` -------------------------------- ### Optimize Independent Awaits with Promise.all Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/function-duration.mdx Detects 3 or more sequential `await` statements that appear independent. If awaits don't reference variables from earlier ones, running them in parallel with `Promise.all()` can significantly cut function duration. ```typescript const users = await db.user.findMany(); const posts = await db.post.findMany(); const comments = await db.comment.findMany(); ``` ```typescript const [users, posts, comments] = await Promise.all([ db.user.findMany(), db.post.findMany(), db.comment.findMany(), ]); ``` -------------------------------- ### Generate AI Fix Prompts with Vercel Doctor CLI Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Exports fix prompts from Vercel Doctor for manual use with AI tools. Supports JSON output for automation and Markdown for copy-pasting. ```bash # Generate JSON prompts for automation npx vercel-doctor . --ai-prompts fixes.json ``` ```bash # Generate Markdown prompts for copy-paste npx vercel-doctor . --ai-prompts fixes.md ``` -------------------------------- ### Run Type Checking Source: https://github.com/aniket-508/vercel-doctor/blob/main/AGENTS.md Perform static type checking to catch potential type-related errors. This is crucial for TypeScript projects. ```bash pnpm typecheck ``` -------------------------------- ### Optimize Function Execution with Promise.all Source: https://context7.com/aniket-508/vercel-doctor/llms.txt This rule detects sequential `await` calls within a function that could be executed in parallel using `Promise.all` to improve performance. ```typescript // Rule: async-parallel // Detects sequential awaits that could run in parallel // Before (slow - sequential execution) const user = await fetchUser(id); const posts = await fetchPosts(id); const comments = await fetchComments(id); // After (fast - parallel execution) const [user, posts, comments] = await Promise.all([ fetchUser(id), fetchPosts(id), fetchComments(id) ]); ``` -------------------------------- ### Avoid `cache: "no-store"` or `revalidate: 0` in Fetch Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/caching.mdx Disabling fetch caching with `cache: "no-store"` or `revalidate: 0` increases uncached bandwidth and compute costs. Configure a revalidation period for effective caching. ```typescript const data = await fetch(url, { cache: "no-store" }); ``` ```typescript const data = await fetch(url, { next: { revalidate: 3600 }, }); ``` -------------------------------- ### Add `sizes` to `` with `fill` Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/image-optimization.mdx Detects `` components using the `fill` prop without a `sizes` attribute. This causes the browser to download the largest available image, wasting bandwidth and increasing optimization usage. ```typescript Hero ``` ```typescript Hero ``` -------------------------------- ### Avoid Client Fetch in Server Components - Next.js Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/invocations.mdx Detects `useEffect` + `fetch` patterns in page or layout files. Fetching data server-side in a Server Component eliminates the API round-trip entirely. ```tsx "use client"; import { useEffect, useState } from "react"; export default function Page() { const [data, setData] = useState(null); useEffect(() => { fetch("/api/data") .then((res) => res.json()) .then(setData); }, []); return
{data?.title}
; } ``` ```tsx export default async function Page() { const data = await fetchData(); return
{data.title}
; } ``` -------------------------------- ### Parallelize Awaits in Edge Runtime Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/function-duration.mdx Detects edge runtime files with 2 or more sequential `await` calls without `Promise.all`. Edge functions have strict execution time limits, and parallelizing I/O operations can save precious milliseconds. ```typescript export const runtime = "edge"; export async function GET() { const user = await getUser(); const settings = await getSettings(); return Response.json({ user, settings }); } ``` ```typescript export const runtime = "edge"; export async function GET() { const [user, settings] = await Promise.all([getUser(), getSettings()]); return Response.json({ user, settings }); } ``` -------------------------------- ### Restrict `remotePatterns` in `next.config.js` Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/image-optimization.mdx Detects overly broad `pathname` patterns in `images.remotePatterns`. Unrestricted paths can lead to unexpected optimization usage from user-generated content or third-party embeds. ```javascript // next.config.js module.exports = { images: { remotePatterns: [{ hostname: "cdn.example.com", pathname: "/**" }], }, }; ``` ```javascript // next.config.js module.exports = { images: { remotePatterns: [{ hostname: "cdn.example.com", pathname: "/avatars/**" }], }, }; ``` -------------------------------- ### Configure Vercel Crons Externally Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Avoid using Vercel's built-in `crons` configuration in `vercel.json` for frequent tasks. Consider using external services like GitHub Actions scheduled workflows to reduce function invocations. ```json // Rule: vercel-avoid-platform-cron // Suggests moving crons to external services // vercel.json (increases function invocations) { "crons": [ { "path": "/api/cleanup", "schedule": "0 0 * * *" } ] } // Alternative: Use GitHub Actions scheduled workflow // .github/workflows/cleanup.yml name: Daily Cleanup on: schedule: - cron: "0 0 * * *" jobs: cleanup: runs-on: ubuntu-latest steps: - run: curl -X POST https://your-app.vercel.app/api/cleanup ``` -------------------------------- ### Add `unoptimized` prop to SVG `` Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/rules/image-optimization.mdx Detects `` components with an SVG `src` that lack the `unoptimized` prop. SVGs do not benefit from the Image Optimization pipeline, and processing them wastes optimization quota. ```typescript Logo ``` ```typescript Logo ``` -------------------------------- ### Ignoring Specific Rules Source: https://github.com/aniket-508/vercel-doctor/blob/main/packages/website/content/docs/en/configuration.mdx Specify rule IDs in the `ignore.rules` array to prevent Vercel Doctor from flagging them. Use the `plugin/rule` format for rule IDs. ```json { "ignore": { "rules": [ "vercel-doctor/nextjs-image-missing-sizes", "vercel-doctor/vercel-large-static-asset", "knip/exports" ] } } ``` -------------------------------- ### Vercel Doctor Configuration Options (TypeScript Interface) Source: https://context7.com/aniket-508/vercel-doctor/llms.txt Defines the available configuration options for Vercel Doctor, including `ignore` for rules and files, and flags for `lint`, `deadCode`, `verbose`, and `diff` modes. ```typescript interface VercelDoctorConfig { ignore?: { rules?: string[]; // Rules to suppress (e.g., "vercel-doctor/async-parallel") files?: string[]; // File paths/globs to exclude }; lint?: boolean; // Enable lint checks (default: true) deadCode?: boolean; // Enable dead code detection (default: true) verbose?: boolean; // Show file details per rule (default: false) diff?: boolean | string; // Force diff mode or pin base branch } ```