DEV Community

Cover image for Simple file based routing for Express
Matthias
Matthias

Posted on

Simple file based routing for Express

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

This approach can work for you out-of-the-box too!

npm install express-file-routing
Enter fullscreen mode Exit fullscreen mode

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([])
}
Enter fullscreen mode Exit fullscreen mode

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({})
  }
]
Enter fullscreen mode Exit fullscreen mode

See matthiaaas/express-file-routing on GitHub for detailed docs & a get started guide.

Top comments (4)

Collapse
 
estotriramdani profile image
Esto Triramdani N • Edited

I found your project is interesting. I am gonna explore it in my next project ✈️💻

Collapse
 
matthiaaas profile image
Matthias

Thank you, let me know @estotriramdani!

Collapse
 
christopherkapic profile image
CK • Edited

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?

Collapse
 
matthiaaas profile image
Matthias

Thank you @christopherkapic!