DEV Community

Willyams Yujra
Willyams Yujra

Posted on • Edited on

Create API Routing in Express with Vite

Introduction

In this tutorial, we will learn how to enhance API routing in Vite using the "vite-plugin-api" 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:

  • Basic knowledge of ViteJS, Node.js, and Express.
  • An existing Vite project.

Step 1: Installation

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

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

Step 2: Configuration

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

import { defineConfig } from "vite";
import { pluginAPI } from "vite-plugin-api";
export default defineConfig({
  plugins: [
    pluginAPI({
      // 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/:
├───v1
│   │   auth.js
│   │   index.js
│   ├───auth
│   │       login.js
│   │       status.js
│   └───user
│           $userId.js    //Remix Format
│           [userId].js    //NextJS Format
│           index.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/v1/user/$userId.js file, you can export the DELETE and PUT methods:

//file:src/api/v1/user/$userId.js
export const DELETE = (req, res, next) => {
  res.send("DELETE REQUEST");
};
export const PUT = async (req, res, next) => {
  res.send("PUT REQUEST");
};
Enter fullscreen mode Exit fullscreen mode

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

Step 5: 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.

You can see the full example in: https://github.com/yracnet/vite-plugin-api

Conclusion

Congratulations! You have successfully enhanced API routing in your Vite project using the "vite-plugin-api" 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!

Top comments (0)