DEV Community

Cover image for Express file-based routing like Next.js
Matthias
Matthias

Posted on

Express file-based routing like Next.js

File-based routing is a popular approach to mapping route handlers to their corresponding publicly-available URL endpoints. You might be quite familiar with it thanks to modern JavaScript frameworks like Next.js.

With the express-file-routing package, you can leverage that routing solution for your own Express.js projects and ditch writing a lot of controller boilerplate code.

// routes/users.ts
export const get = async (req, res) => {
  const users = db.users.findMany()
  return res.json(users)
}
Enter fullscreen mode Exit fullscreen mode

Your project's file structure might look like the following:

├── app.ts // main file
├── routes
    ├── index.ts // index routes
    ├── posts
        ├── index.ts
        └── [slug].ts // dynamic params
    └── users.ts
└── package.json
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

How to use Express file routing

This is quite of a straightforward process. Even though this post is more of an intro rather than a tutorial on how to use express-file-routing, here's a quick start.

All you need to do is to install express-file-routing from npm.

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

In your main entry file, create an Express app instance and attach the file router.

// app.ts
import express from "express"
import { router } from "express-file-routing"

const app = express()

app.use("/", await router())

app.listen(4000)
Enter fullscreen mode Exit fullscreen mode

You're already done!

Enqueuing new routes from now on is as easy as creating a file in /routes and exporting your HTTP method handlers.

// routes/posts/index.ts → /posts
export const get = async (req, res) => {
    return res.json([])
}

export const post = [
  async (req, res) => {
    const post = await db.post.create()
    return res.status(201).json(post)
  }
]
Enter fullscreen mode Exit fullscreen mode

Even middlewares are supported by exporting an array of request handlers instead of a single one.

// routes/users.ts
export const post = [
  userAuth(),
  rateLimit({ window: 10 }), 
  async (req, res) => {
    return res.status(201).json({})
  }
]
Enter fullscreen mode Exit fullscreen mode

For detailed docs check out https://github.com/matthiaaas/express-file-routing.

Top comments (0)