routez
v0.1.0
Published
Next.JS like file-based routing for Express.js
Maintainers
Readme
Routez
Routez is a simple and lightweight Express based package that allows you to create routes using the file-based routing system similar to NextJS. Which means,
NO MORE ROUTE IMPORTS! 🎉and
app.use("/api", require("./routes/api"));If you're interested in NextJS or you've already used it in past, you'll feel right at home. 😁
Getting Started
Initialize a new Node.js project,
npm init -y # or yarn init -y # or pnpm init -y # or bun init -yInstall the package,
npm install routez # or yarn add routez # or pnpm add routez # or bun add routezCreate a new file named
server.jsand add the following code,import path from "path"; import express from "express"; import { createRouter } from "routez"; const port = process.env.PORT || 3001; const app = express(); createRouter(app); app.listen(port, () => { console.log("Server started on port " + port); });We suggest using TypeScript for better type safety. If you want to use TypeScript, create a new file named
server.tsinstead ofserver.js.If you've a
srcdirectory, just add this code and make sure to add theserver.jsfile inside thesrcdirectory.createRouter(app, { directory: path.join(process.cwd(), "src/server"), });
Create a new directory named
appin the root directory of your project (or insidesrc, if you have one), and create another directory namedapiinside theappdirectory.Create a new folder named
usersinside theapidirectory and create a new file namedroute.jsinside theusersdirectory.export function GET(req, res) { res.json({ message: "GET users" }); }Run the server using the following command,
node server.jsOpen your browser and navigate to
http://localhost:3001/api/users. You should see the following JSON response,{ "message": "GET users" }That's it! You've successfully created your first route using Routez. 🎉
If you're using
routezwith JavaScript, make sure to useimportstatements instead ofrequirestatements. This package does not support CommonJS modules.
Features
- File-based Routing (similar to NextJS): No more route imports! Just create a new file in the
appdirectory and it will be automatically registered as a route. - TypeScript: Written in TypeScript, so no more type errors!
Configuration
The configuration is done in the createRouter function in here. This function is invoked in the app.ts file. The createRouter function takes two arguments,
| Option | Type | Default | Description | Required |
| -------------------- | --------- | --------------------------------- | ------------------------------------------- | -------- |
| app | Express | undefined | The Express app instance. | Yes |
| options | Options | {} | The options object. | No |
| options.direrctory | string | path.join(process.cwd(), "app") | The directory where the routes are located. | No |
If you want to change the directory where the routes are located, you can do it by changing the options.directory option. Here's an example,
// ... Your existing imports ...
import path from "path";
import express from "express";
import { createRouter } from "./lib";
export function createApp() {
const app = express();
// ... Your existing code ...
createRouter(app, {
directory: path.join(process.cwd(), "routes"),
});
// ... Your existing code ...
return app;
}Now, all the routes will be loaded from the routes directory instead of the app directory.
Routes
The routes are defined in the examples/src/app directory. Here's how you can define a route:
src
└── app
└── api
├── users
│ ├── route.ts
│ └── [userId]
│ └── route.ts
├── blogs
│ └── route.ts
└── uploads
└── route.ts- The
appdirectory is the root directory for all the routes. - The
apidirectory is the root directory for all the API routes. Although, you can change this name to anything you want. - The
usersdirectory is a route for the/userspath. - The
route.tsfile is the entry point for the/userspath.- See here for an example.
- The
[userId]directory is a route for the/users/:userIdpath.- The
:userIdis a dynamic parameter. You can access it usingreq.params.userId. - See here for an example.
- The
- Files that are inside the
apidirectory must follow the rules written below,- The file must be named as
route.ts/route.js. This is the entry point for the route. - The file named
route.tsmust not have a default export. - These files can have named exports (GET, POST, PUT, DELETE, etc.).
- See here for an example.
- The file must be named as
Defining Dynamic Routes
- Dynamic routes are supported both in the
apidirectory and outside of it. - To define a dynamic route, create a directory with the name of the dynamic parameter inside the directory of the route.
- For example, to define a dynamic route for
/users/:userId, create a directory named[userId]inside theusersdirectory. - The name of the directory must be the same as the name of the dynamic parameter.
- You can access the dynamic parameter using
req.params.userIdinside theroute.tsfile. - See here for an example.
Adding Middleware
You can,
Add middleware to the whole application by adding it to the
app.usefunction in the app.ts file.Or add middleware to a specific route by converting the exported function to an array of functions. See here for an example.
import { Request, Response } from "express"; import multer from "multer"; const upload = multer({ dest: "uploads/" }); export const POST = [ upload.single("file"), (req: Request, res: Response) => { res.json({ file: req.file, }); }, ];Thus, the
POSTfunction is now an array of functions. The first function is themultermiddleware and the second function is the actual route handler.You can add as many middleware as you want. Just make sure that the last function is the actual route handler.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Feedback
Feel free to send me feedback on X or file an issue. Feature requests are always welcome. If you wish to contribute, please take a quick look at the guidelines!
Join our Discord server here!
