There are a bunch of best practices out there that recommend to split your Express.js routes into separate files using Express.Router()
.
But creating new routes this way isn't straightforward and requires quite a few lines of boilerplate code for each newly introduced endpoint.
// this is messy
import express from "express"
const router = express.Router()
router.route("/")
.get(async (req, res) => {
...
})
export default router
Fortunately, the framework era taught us better and popularized cleaner alternatives like file based routing.
Consider the following project structure:
├── app.ts // main file
├── routes
├── index.ts // index routes
├── posts
├── index.ts
└── [id].ts // dynamic params
└── users.ts
└── package.json
This approach can work for you out-of-the-box too!
npm install express-file-routing
express-file-routing
will transform all of your files inside /routes
into valid paths.
-
/routes/index.ts
→ / -
/routes/posts/index.ts
→ /posts -
/routes/posts/[id].ts
→ /posts/:id -
/routes/users.ts
→ /users
// app.ts
import express from "express"
import { router } from "express-file-routing"
const app = express()
app.use(router())
// /routes/users.ts
export const get = async (req, res) => {
res.json([])
}
By default, exported functions like get
, post
, put
, patch
, del
etc. will get matched their corresponding HTTP method automatically.
Adding middlewares is equally intuitive:
// /routes/posts.ts
import { rateLimit, userAuth } from "../middlewares"
export const post = [
rateLimit(), userAuth(),
async (req, res) => {
res.status(201).json({})
}
]
See matthiaaas/express-file-routing on GitHub for detailed docs & a get started guide.
Top comments (4)
I found your project is interesting. I am gonna explore it in my next project ✈️💻
Thank you, let me know @estotriramdani!
Thank you! I can't believe this hasn't gotten more attention. I see you're still maintaining the project, which is awesome. Do you have a place where we can donate?
Thank you @christopherkapic!