Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 17, 2021 10:53 am GMT

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 messyimport 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.tsimport express from "express"import { router } from "express-file-routing"const app = express()app.use(router())// /routes/users.tsexport 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.tsimport { 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.


Original Link: https://dev.to/matthiaaas/simple-file-based-routing-for-express-1l22

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To