![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
vite-plugin-api-routes
Advanced tools
A Vite.js plugin that creates API routes by mapping the directory structure, similar to Next.js API Routes. This plugin enhances the functionality for backend development using Vite.
🙏 Dear Community,
We sincerely apologize for the recent project name changes. After careful consideration and feedback, we've settled on the name vite-plugin-api-routes. We understand that these changes might have caused confusion, and we appreciate your understanding.
Thank you for your continued support and flexibility.
Best regards,
For more detailed information and resources related to vite-plugin-api-routes
, please refer to the following:
Enhance API routing in ViteJS based on directory structure for improved visibility and project structure in Node.js and Express.
See the tutorial
> tree src/api/
src/api/:
├───admin
│ ├───auth
│ │ ├───login.js
│ │ └───status.js
│ └───user
│ ├───index.js
│ └───[userId] //Remix Format
│ ├───index.js
│ └───detail.js
├───site
│ ├───article
│ │ ├───$articleId.js //NextJS Format
│ │ └───new.js
│ └───page
│ ├───$pageId.js
│ └───new.js
└───index.js
The directory tree is exported as router rules tree:
GET /api/site/
GET /api/routers
USE /api/admin/user
GET /api/admin/user
GET /api/admin/user/
POST /api/admin/user/
GET /api/admin/auth/login
POST /api/admin/auth/login
GET /api/site/article/new
GET /api/admin/auth/status
POST /api/admin/auth/status
GET /api/site/page/:pageId
GET /api/admin/user/:userId/
PUT /api/admin/user/:userId/
DELETE /api/admin/user/:userId/
GET /api/site/article/:articleId
GET /api/admin/user/:userId/detail
For example, the src/api/admin/user/$userId.js
file exports allowed request methods:
//file:src/api/admin/user/$userId.js
export const DELETE = (req, res, next) => {
res.send("DELETE REQUEST");
};
export const PUT = async (req, res, next) => {
res.send("PUT REQUEST");
};
// Support default, GET, HEAD, POST, PUT, DELETE by default
// For CONNECT, OPTIONS, TRACE, PATCH, and others, you need to add the mapping to the mapper attribute config
// If you need middlewares for a route, simply export an array containing all middlewares as the default
export default [authMiddleware, secondMiddleware /* ... */];
Similarly, the [userId].js
or $userId.js
file name is exported as a request parameter /user/:userId
, following the Next.js/Remix framework.
yarn add vite-plugin-api-routes
In order to have proper access to the plugin's alias definitions, you need to include /.api/env.d.ts
in either src/vite-env.d.ts
or in your tsconfig.json
.
In your src/vite-env.d.ts
, add the following line:
/// <reference path="../.api/env.d.ts" />
In vite.config.ts
:
import { defineConfig } from "vite";
import { pluginAPIRoutes } from "vite-plugin-api-routes";
export default defineConfig({
plugins: [
pluginAPIRoutes({
// moduleId: "@api",
// cacheDir: ".api",
// server: "[cacheDir]/server.js",
// handler: "[cacheDir]/handler.js",
// configure: "[cacheDir]/configure.js",
// routeBase: "api",
// dirs: [{ dir: "src/api"; route: "", exclude?: ["*.txt", ".csv", "data/*.*"] }],
// include: ["**/*.js", "**/*.ts"],
// exclude: ["node_modules", ".git"],
// mapper: { default: "use", GET: "get", ... },
// disableBuild: false,
// clientOutDir = "dist/client",
// clientMinify = true,
// clientBuild = (config: InlineConfig) => config,
// serverOutDir = "dist",
// serverMinify = false,
// serverBuild = (config: InlineConfig) => config,
}),
],
});
Note: When building the project, the server entry will be built first, before the client is compiled.
Default Value
mapper: {
//[Export Name]: [Http Verbose]
default: "use",
GET: "get",
POST: "post",
PUT: "put",
PATCH: "patch",
DELETE: "delete",
// Overwrite
...mapper,
};
/vite.config.js
export default defineConfig({
plugins: [
pluginAPIRoutes({
mapper: {
/**
* export const PING = ()=>{...}
* Will be mapped to express method
* app.get('/path/dir', PING)
*/
PING: "get",
/**
* export const OTHER_POST = ()=>{...}
* Will be mapped to possible method
* app.post2('/path/dir', OTHER_POST)
*/
OTHER_POST: "post2",
/**
* export const PATCH = ()=>{...}
* Will not be mapped
*/
PATCH: false,
},
}),
],
});
You can disable a method by setting its value to false. In the example PATCH: false
, the PATCH method is disabled.
/src/api/index.js
export const PING = (req, res, next) => {
res.send({ name: "Ping Service" });
};
export const OTHER_POST = (req, res, next) => {
res.send({ name: "Other Service" });
};
export const PATCH = (req, res, next) => {
res.send({ name: "Path Service" });
};
/src/handler.js or see handler.js
import express from "express";
import { applyRouters } from "@api/routers";
import * as configure from "@api/configure";
export const handler = express();
configure.handlerBefore?.(handler);
applyRouters((props) => {
const { method, route, path, cb } = props;
if (handler[method]) {
if (Array.isArray(cb)) {
handler[method](route, ...cb);
} else {
handler[method](route, cb);
}
} else {
console.log("Not Support", method, "for", route, "in", handler);
}
});
configure.handlerAfter?.(handler);
/src/server.ts or see server.ts
import { handler } from "@api/handler";
import { endpoints } from "@api/routers";
import * as configure from "@api/configure";
import express from "express";
const server = express();
configure.serverBefore?.(server);
const { PORT = 3000, PUBLIC_DIR = "import.meta.env.PUBLIC_DIR" } = process.env;
server.use("import.meta.env.BASE", express.static(PUBLIC_DIR));
server.use("import.meta.env.BASE_API", handler);
configure.serverAfter?.(server);
server.on("error", (error) => {
console.error(`Error at http://localhost:${PORT}`, error);
configure.serverError?.(server, error);
});
server.on("listening", () => {
console.log(`Ready at http://localhost:${PORT}`);
configure.serverListening?.(server, endpoints);
});
server.listen(PORT);
/src/configure.ts or see configure.ts
import express from "express";
import {
CallbackHook,
StatusHook,
ServerHook,
HandlerHook,
ViteServerHook,
} from "vite-plugin-api-routes/configure";
// import { ApplyRouter, ApplyRouters } from "vite-plugin-api-routes/routes"
// import { Callback, RouteInfo, RouteModule } from "vite-plugin-api-routes/handler"
export const serverBefore: ServerHook = (server) => {};
export const serverAfter: ServerHook = (server) => {};
export const serverListening: StatusHook = (server, endpoints) => {};
export const serverError: StatusHook = (server, error) => {};
export const handlerBefore: HandlerHook = (handler) => {};
export const handlerAfter: HandlerHook = (handler) => {};
export const viteServerBefore: ViteServerHook = (server) => {};
export const viteServerAfter: ViteServerHook = (server) => {};
FAQs
A Vite.js plugin that creates API routes by mapping the directory structure, similar to Next.js API Routes. This plugin enhances the functionality for backend development using Vite.
The npm package vite-plugin-api-routes receives a total of 6 weekly downloads. As such, vite-plugin-api-routes popularity was classified as not popular.
We found that vite-plugin-api-routes demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.