Vite Plugin for File-System API Routes

1.3.0-beta1 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `vite-plugin-api-routes` in `vite.config.ts` to enable file-system based API routing. It sets up the plugin to serve routes from `src/api` under the `/api` URL prefix using `ISOLATED` mode, and includes a simple `GET` route handler for `/api/hello`.

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

view raw JSON →