DEV Community

Willyams Yujra
Willyams Yujra

Posted on

Isolated API Routing in ViteJS with `vite-plugin-api-routes`

Tutorial: Isolated API Routing in ViteJS with vite-plugin-api-routes

Introduction

In this tutorial, we will learn how to enhance isolated API routing in ViteJS using the vite-plugin-api-routes plugin. This plugin improves visibility and project structure in Node.js and Express by mapping the directory structure to route rules.

Prerequisites

Before we begin, make sure you have the following:

Step 1: Installation

To install the vite-plugin-api-routes plugin, run the following command:

yarn add vite-plugin-api-routes
Enter fullscreen mode Exit fullscreen mode

Step 2: Configuration

In your ViteJS project, open the vite.config.ts file and add the following code:

import { defineConfig } from "vite";
import apiRoutes from "vite-plugin-api-routes";

export default defineConfig({
  plugins: [
    apiRoutes({
      mode: "isolated",
      // Configuration options go here
    }),
  ],
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Directory Structure

Next, let's create the API directory structure in your project's source folder (src/api). Here's an example structure:

> tree src/api/
src/api/:
└───user
    ├───USE.js
    ├───GET.js
    ├───POST.js
    └───[userId]          // NextJS Format
        ├───GET.js
        ├───PUT.js
        └───DELETE.js
Enter fullscreen mode Exit fullscreen mode

Step 4: Exporting Route Rules

In each API file within the directory structure, you can export the allowed request methods. For example, in the src/api/user/[userId]/DELETE.js file, you can export the default method for DELETE:

///file:src/api/user/[userId]/DELETE.js
export default (req, res, next) => {
  res.send("DELETE REQUEST");
};
Enter fullscreen mode Exit fullscreen mode

Similarly, the file names GET.js or POST.js will be exported as request parameters, such as /user/:userId/, following the Next.js/Remix framework.

Step 5: Add Middlewares

For every route you can export an array for middlewares. This can be used for authentication purposes or any other sort of middleware that you need.

///file:src/api/user/[userId]/DELETE.js
import authMiddleware from "...";

const USER_DELETE = (req, res, next) => {
  res.send("DELETE REQUEST");
};

export default [authMiddleware, USER_DELETE];
Enter fullscreen mode Exit fullscreen mode

Step 6: Configure Aliases

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. This will allow you to use the alias correctly throughout your project.

Option 1: Add to vite-env.d.ts

In your src/vite-env.d.ts, add the following line:

/// <reference path="../.api/env.d.ts" />
Enter fullscreen mode Exit fullscreen mode

Step 7: Run the Server

Now, you can start the server using ViteJS, and the API routes will be automatically generated based on the directory structure and exported route rules.

Conclusion

Congratulations! You have successfully enhanced API routing in your ViteJS project using the vite-plugin-api-routes plugin. This improves project structure and simplifies configuration, making your development process more efficient.

Remember to refer to the plugin's documentation for more advanced configuration options and customization possibilities.

Happy coding!

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay