Simple file based routing for Express

matthiaaas

Matthias

Posted on October 17, 2021

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.

💖 💪 🙅 🚩
matthiaaas
Matthias

Posted on October 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Simple file based routing for Express
express Simple file based routing for Express

October 17, 2021