Vite Plugin for File-System API Routes
vite-plugin-api-routes is a Vite.js plugin designed to streamline backend API development by implementing a file-system based routing approach, reminiscent of Next.js API Routes. It automatically converts a designated directory structure into API endpoints, enhancing project organization and visibility for Node.js and Express applications integrated with Vite. The package is currently in a beta phase, with version `1.3.0-beta1`, indicating active development. Key differentiators include two distinct routing modes: "ISOLATED" where each HTTP method resides in its own file for explicit endpoint declaration, and "LEGACY" allowing multiple methods within a single file for simpler APIs. It also provides a priority mapping system to precisely control middleware execution order, supporting advanced API configurations. While in beta, its robust features aim to simplify full-stack Vite projects.
Common errors
-
Error: [vite-plugin-api-routes] No API routes found in configured directory: /path/to/your/project/src/api
cause The `dir` option in the plugin configuration points to a non-existent or empty directory, or the path is incorrect relative to `process.cwd()`.fixVerify the `dir` path in `vite.config.ts` is correct and contains valid API route files (e.g., `GET.ts`, `index.ts`). It's recommended to use `path.resolve(process.cwd(), 'your/path')` for robust absolute path resolution. -
404 Not Found response for an API endpoint that should exist.
cause The `base` option in the plugin configuration doesn't match the URL prefix being accessed, or the route file name/structure doesn't match the expected path based on the chosen `mode`.fixCheck that the `base` option (e.g., `/api`) matches the URL prefix used in your client-side requests (e.g., `fetch('/api/my-route')`). Also, ensure your route files (e.g., `src/api/my-route/GET.ts`) correctly map to the desired endpoint according to the `ISOLATED` or `LEGACY` routing mode. -
TypeError: Cannot read properties of undefined (reading 'json') or similar Express-related errors within route handlers.
cause The API route handler is not correctly exporting a default function, or the function signature does not match Express's `(req, res, next)` expectation, leading to `res` (or other Express objects) being undefined or not having expected methods.fixEnsure your API route files `export default` an Express-compatible handler function, e.g., `export default (req, res) => { res.status(200).json(...) }`. Also, ensure `express` is installed if you are using its types or features directly.
Warnings
- breaking The package is currently in beta (`1.3.0-beta1`). The API, features, and internal implementation may change significantly before a stable `1.0` release, potentially introducing breaking changes for users relying on pre-release versions.
- gotcha The plugin offers two distinct routing modes: `ISOLATED` (one file per HTTP method, e.g., `GET.ts`) and `LEGACY` (multiple methods via named exports in a single `index.ts` file). Mixing paradigms or misunderstanding the implications can lead to unexpected route resolution or missed endpoints.
- gotcha While the `mapper` attribute allows for fine-grained control over middleware execution priority, incorrect or overlapping priority definitions, especially with `USE` methods, can lead to unexpected middleware bypasses or incorrect request handling order.
Install
-
npm install vite-plugin-api-routes -
yarn add vite-plugin-api-routes -
pnpm add vite-plugin-api-routes
Imports
- api
const api = require('vite-plugin-api-routes');import api from 'vite-plugin-api-routes';
- Request, Response (types)
import { Request, Response } from 'express';import type { Request, Response } from 'express';
Quickstart
// vite.config.ts
import { defineConfig } from 'vite';
import apiRoutes from 'vite-plugin-api-routes';
import path from 'node:path';
export default defineConfig({
plugins: [
apiRoutes({
// Specifies the root directory where your API route files are located.
// This example uses 'src/api' relative to the project root.
dir: path.resolve(process.cwd(), 'src/api'),
// Defines the base URL path under which these API routes will be served.
// e.g., files in 'src/api/hello/GET.ts' will be accessible under '/api/hello'
base: '/api',
// Choose a routing mode: 'ISOLATED' (default) or 'LEGACY'.
// 'ISOLATED' means one file per HTTP method (e.g., GET.ts, POST.ts).
// 'LEGACY' means a single index.ts can export multiple method handlers.
mode: 'ISOLATED'
})
]
});
// src/api/hello/GET.ts (create this file)
// This file will handle GET requests to /api/hello
import type { Request, Response } from 'express';
export default (req: Request, res: Response) => {
res.status(200).json({ message: 'Hello from Vite API Routes!', method: req.method });
};
// To run:
// 1. Create vite.config.ts and src/api/hello/GET.ts in your project root.
// 2. npm install vite vite-plugin-api-routes express @types/express
// 3. Add "dev": "vite" to your package.json scripts.
// 4. Run `npm run dev` and visit http://localhost:5173/api/hello in your browser.