{"id":21148022,"url":"https://github.com/matthiaaas/express-file-routing","last_synced_at":"2025-04-08T03:14:26.913Z","repository":{"id":42505106,"uuid":"384222319","full_name":"matthiaaas/express-file-routing","owner":"matthiaaas","description":"Flexible file-based routing for Express (like Next.js + additional features)","archived":false,"fork":false,"pushed_at":"2024-07-10T10:06:52.000Z","size":237,"stargazers_count":85,"open_issues_count":2,"forks_count":13,"subscribers_count":4,"default_branch":"main","last_synced_at":"2024-10-30T07:43:32.868Z","etag":null,"topics":["express","file","file-based","router","routing"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/express-file-routing","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/matthiaaas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-07-08T18:58:56.000Z","updated_at":"2024-10-16T09:28:09.000Z","dependencies_parsed_at":"2024-02-29T23:26:22.047Z","dependency_job_id":"aac05764-0ffc-4235-89a9-75dbccd8a38d","html_url":"https://github.com/matthiaaas/express-file-routing","commit_stats":{"total_commits":127,"total_committers":6,"mean_commits":"21.166666666666668","dds":"0.047244094488189003","last_synced_commit":"f0439be686b4ba045903ca7f901cb7b2bb70ac12"},"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/matthiaaas%2Fexpress-file-routing","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/matthiaaas%2Fexpress-file-routing/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/matthiaaas%2Fexpress-file-routing/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/matthiaaas%2Fexpress-file-routing/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/matthiaaas","download_url":"https://codeload.github.com/matthiaaas/express-file-routing/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247256092,"owners_count":20909240,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["express","file","file-based","router","routing"],"created_at":"2024-11-20T09:20:27.088Z","updated_at":"2025-04-08T03:14:26.868Z","avatar_url":"https://github.com/matthiaaas.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# express-file-routing\n\n![GitHub release (latest by date)](https://img.shields.io/github/v/release/matthiaaas/express-file-routing?color=brightgreen\u0026label=latest)\n\nFlexible file-based routing for Express with `0` dependencies.\n\n## Installation\n\n```bash\nnpm install express-file-routing\n```\n\n**Note:** If you prefer `yarn` instead of `npm`, just use `yarn add express-file-routing`.\n\n## How to use\n\nFundamentally, there are two ways of adding this library to your codebase: **either** as a middleware with `app.use(\"/\", await router())`, which will add a separate [sub-router](http://expressjs.com/en/5x/api.html#router) to your app, **or** by wrapping your whole Express instance with `await createRouter(app)`, which will bind the routes directly to your app instance. In most cases, it doesn't matter on what option you decide, even though one or the other might perform better in some scenarios.\n\n- app.ts (main)\n\n```ts\nimport express from \"express\"\nimport createRouter, { router } from \"express-file-routing\"\n\nconst app = express()\n\n// Option 1\napp.use(\"/\", await router()) // as router middleware or\n\n// Option 2\nawait createRouter(app) // as wrapper function\n\napp.listen(2000)\n```\n\n**Note:** By default, routes are expected to be located in your project's `/routes` directory.\n\n- routes/index.ts\n\n```ts\nexport const get = async (req, res) =\u003e {\n  if (req.method !== \"GET\") return res.status(405)\n\n  return res.json({ hello: \"world\" })\n}\n```\n\n#### Directory Structure\n\nFiles inside your project's `/routes` directory will get matched an url path automatically.\n\n```php\n├── app.ts\n├── routes\n    ├── index.ts // index routes\n    ├── posts\n        ├── index.ts\n        └── [id].ts or :id.ts // dynamic params\n    └── users.ts\n└── package.json\n```\n\n- `/routes/index.ts` → /\n- `/routes/posts/index.ts` → /posts\n- `/routes/posts/[id].ts` → /posts/:id\n- `/routes/users.ts` → /users\n\n**Note:** Files prefixed with an underscore or ending with `.d.ts` are excluded from route generation.\n\n## API\n\n```ts\nawait createRouter(app, {\n  directory: path.join(__dirname, \"routes\"),\n  additionalMethods: [\"ws\", ...]\n})\n// or\napp.use(\"/\", await router({\n  directory: path.join(__dirname, \"routes\"),\n  additionalMethods: [\"ws\", ...],\n  routerOptions: express.RouterOptions\n}))\n```\n\n### Options\n\n- `directory`: The path to the routes directory (defaults to `/routes`)\n- `additionalMethods`: Additional methods that match an export from a route like `ws` (e.g. `ws` for express-ws)\n- `routerOptions`: Native Express [Router Options](https://expressjs.com/de/api.html#express.router) objects forwarded as-is to the underlying router\n\n## Examples\n\n### HTTP Method Matching\n\nIf you export functions named e.g. `get`, `post`, `put`, `patch`, `delete`/`del` [etc.](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) from a route file, those will get matched their corresponding http method automatically.\n\n```ts\nexport const get = async (req, res) =\u003e { ... }\n\nexport const post = async (req, res) =\u003e { ... }\n\n// since it's not allowed to name constants 'delete', try 'del' instead\nexport const del = async (req, res) =\u003e { ... }\n\n// you can still use a wildcard default export in addition\nexport default async (req, res) =\u003e { ... }\n```\n\n**Note:** Named method exports gain priority over wildcard exports (= default exports).\n\n### Middlewares\n\nYou can add isolated, route specific middlewares by exporting an array of Express request handlers from your route file.\n\n```ts\n// routes/dashboard\nimport { rateLimit, bearerToken, userAuth } from \"../middlewares\"\n\nexport const get = [\n  rateLimit(), bearerToken(), userAuth(),\n  async (req, res) =\u003e { ... }\n]\n```\n\nA middleware function might look like the following:\n\n```ts\n// middlewares/userAuth.ts\nexport default (options) =\u003e async (req, res, next) =\u003e {\n  if (req.authenticated) next()\n  ...\n}\n```\n\n### Custom Methods Exports\n\nYou can add support for other method exports to your route files. This means that if your root app instance accepts non built-in handler invocations like `app.ws(route, handler)`, you can make them being recognized as valid handlers.\n\n```ts\n// app.ts\nimport ws from \"express-ws\"\n\nconst { app } = ws(express())\n\nawait createRouter(app, {\n  additionalMethods: [\"ws\"]\n})\n\n// routes/index.ts\nexport const ws = async (ws, req) =\u003e {\n  ws.send(\"hello world\")\n}\n```\n\n### Usage with TypeScript\n\nThe library itself comes with built-in type definitions. Adding support for route \u0026 method handler type definitions is as straightforward as including Express' native `Handler` type from [@types/express](https://www.npmjs.com/package/@types/express).\n\n```ts\n// routes/posts.ts\nimport type { Handler } from \"express\"\n\nexport const get: Handler = async (req, res, next) =\u003e { ... }\n```\n\n### Error Handling\n\nIt is essential to catch potential errors (500s, 404s etc.) within your route handlers and forward them through `next(err)` if necessary, as treated in the Express' docs on [error handling](https://expressjs.com/en/guide/error-handling.html).\n\nDefining custom error-handling middleware functions should happen _after_ applying your file-system routes.\n\n```ts\napp.use(\"/\", await router()) // or 'await createRouter(app)'\n\napp.use(async (err, req, res, next) =\u003e {\n  ...\n})\n```\n\n### Catch-All (unstable)\n\nThis library lets you extend dynamic routes to catch-all routes by prefixing them with three dots `...` inside the brackets. This will make that dynamic route match itself but also all subsequent routes within that route.\n\n**Note:** Since this feature got added recently, it might be unstable. Feedback is welcome.\n\n```ts\n// routes/users/[...catchall].js\nexport const get = async (req, res) =\u003e {\n  return res.json({ path: req.params[0] })\n}\n```\n\n- `routes/users/[...catchall].js` matches /users/a, /users/a/b and so on, but **not** /users.\n\n## Migrating from v2\n\nThe latest version v3 fixed stable support for ESM \u0026 CJS compatibility, but also **introduced a breaking change** in the library's API. To upgrade, first install the latest version from npm.\n\n### Upgrade version\n\n```\nnpm install express-file-routing@latest\n```\n\n### Await the router\n\nRegistering the file-router in v2 was synchronous. Newer versions require to await the router. So the only change in your codebase will be to await the router instead of calling it synchronously:\n\n```diff\nconst app = express()\n\n- app.use(\"/\", router())\n+ app.use(\"/\", await router())\n\napp.listen(2000)\n```\n\nOr if you were using `createRouter()`:\n\n```diff\nconst app = express()\n\n- createRouter(app)\n+ await createRouter(app)\n\napp.listen(2000)\n```\n\n**Note:** If your environment does not support top-level await, you might need to wrap you code in an async function.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmatthiaaas%2Fexpress-file-routing","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmatthiaaas%2Fexpress-file-routing","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmatthiaaas%2Fexpress-file-routing/lists"}