DEV Community

Cover image for Simple file based routing for Express
Matthias
Matthias

Posted on

7 2

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay