{"id":13716031,"url":"https://github.com/Masquerade-Circus/micro-ex-router","last_synced_at":"2025-05-07T05:32:04.908Z","repository":{"id":22468157,"uuid":"96332105","full_name":"Masquerade-Circus/micro-ex-router","owner":"Masquerade-Circus","description":"Express like router for micro.","archived":false,"fork":false,"pushed_at":"2023-01-06T01:56:46.000Z","size":1331,"stargazers_count":21,"open_issues_count":11,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-12T20:53:28.082Z","etag":null,"topics":["eslint","express","micro","router"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Masquerade-Circus.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["Masquerade-Circus"],"custom":["https://www.paypal.me/masqueradecircus"]}},"created_at":"2017-07-05T15:06:32.000Z","updated_at":"2022-12-22T20:40:44.000Z","dependencies_parsed_at":"2023-01-13T22:01:10.119Z","dependency_job_id":null,"html_url":"https://github.com/Masquerade-Circus/micro-ex-router","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Masquerade-Circus%2Fmicro-ex-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Masquerade-Circus%2Fmicro-ex-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Masquerade-Circus%2Fmicro-ex-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Masquerade-Circus%2Fmicro-ex-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Masquerade-Circus","download_url":"https://codeload.github.com/Masquerade-Circus/micro-ex-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252823103,"owners_count":21809700,"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":["eslint","express","micro","router"],"created_at":"2024-08-03T00:01:06.329Z","updated_at":"2025-05-07T05:32:01.102Z","avatar_url":"https://github.com/Masquerade-Circus.png","language":"JavaScript","funding_links":["https://github.com/sponsors/Masquerade-Circus","https://www.paypal.me/masqueradecircus"],"categories":["Modules"],"sub_categories":["Routing"],"readme":"[![npm version](https://img.shields.io/npm/v/micro-ex-router.svg?style=flat)](https://npmjs.org/package/micro-ex-router \"View this project on npm\")\n[![Build Status](https://travis-ci.org/Masquerade-Circus/micro-ex-router.svg?branch=master)](https://travis-ci.org/Masquerade-Circus/micro-ex-router)\n[![Dependencies](https://img.shields.io/david/masquerade-circus/micro-ex-router.svg?style=flat)](https://david-dm.org/masquerade-circus/micro-ex-router)\n![](https://img.shields.io/github/issues/masquerade-circus/micro-ex-router.svg)\n![](https://img.shields.io/snyk/vulnerabilities/npm/micro-ex-router.svg)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/521f72fc6d61426783692b62d64a3643)](https://www.codacy.com/app/Masquerade-Circus/micro-ex-router?utm_source=github.com\u0026utm_medium=referral\u0026utm_content=Masquerade-Circus/micro-ex-router\u0026utm_campaign=Badge_Grade)\n[![Maintainability](https://api.codeclimate.com/v1/badges/c1263dd7fb4f90194625/maintainability)](https://codeclimate.com/github/Masquerade-Circus/micro-ex-router/maintainability)\n[![Coverage Status](https://coveralls.io/repos/github/Masquerade-Circus/micro-ex-router/badge.svg?branch=master)](https://coveralls.io/github/Masquerade-Circus/micro-ex-router?branch=master)\n[![License](https://img.shields.io/github/license/masquerade-circus/micro-ex-router.svg)](https://github.com/masquerade-circus/micro-ex-router/blob/master/LICENSE)\n\n# micro-ex-router\n\nExpress style router for zeit's [micro](https://github.com/zeit/micro).\n\n## Table of Contents\n\n-   [Install](#install)\n-   [Features](#features)\n-   [Use](#use)\n-   [Use of subrouters](#use-of-subrouters)\n-   [Use of Compression, CORS and other NodeJs Middlewares](#use-of-compression-cors-and-other-nodejs-middlewares)\n-   [Use of Express middlewares](#use-of-express-middlewares)\n-   [Serve files from a directory and render a string as html](#serve-files-from-a-directory-and-render-a-string-as-html)\n-   [Available methods](#available-methods)\n-   [Parsed body and query by default](#parsed-body-and-query-by-default)\n-   [Tests](#tests)\n-   [Contributing](#contributing)\n-   [Legal](#legal)\n\n## Install\n\nThis is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/):\n\n```bash\n// With npm\n$ npm install micro-ex-router\n// With yarn\n$ yarn add micro-ex-router\n```\n\n## Features\n\n-   [x] Default returned responses.\n-   [x] Parametrized routes.\n-   [x] Parse body by default\n-   [x] Parse query by default\n-   [x] \"Use\" middlewares.\n-   [x] \"Use\" middlewares for each method.\n-   [x] Arrays of middlewares.\n-   [x] Mix single middlewares and array of middlewares.\n-   [x] Use of subrouters.\n-   [x] Serve files directory\n-   [x] Render string as html\n\n## Use\n\n```javascript\nlet micro = require('micro');\nlet Router = require('micro-ex-router');\nlet defaultOptions = {\n  parseBody: true, // Tells the router to parse the body by default\n  limit: '1mb', // How much data is aggregated before parsing at max. It can be a Number of bytes or a string like '1mb'.\n  encoding: 'utf8',\n  acceptedMethods: [\n    'get',\n    'post',\n    'put',\n    'patch',\n    'delete',\n    'head',\n    'options',\n    'use'\n  ] // The methods that will be handled by the router\n};\n\n// Create a new router\nlet router = Router(defaultOptions);\n\nrouter\n  // Use middlewares available for all requests\n  .use((req, res) =\u003e console.log(req.url))\n\n  // Use middlewares available for all requests restricted by each method\n  .get((req, res) =\u003e console.log('This is a get request')) // Only for GET requests\n  .post((req, res) =\u003e console.log('This is a post request')) // Only for POST requests\n  .put((req, res) =\u003e console.log('This is a put request')) // Only for PUT requests\n  .patch((req, res) =\u003e console.log('This is a patch request')) // Only for PATCH requests\n  .delete((req, res) =\u003e console.log('This is a delete request')) // Only for DELETE requests\n  .head((req, res) =\u003e console.log('This is a head request')) // Only for HEAD requests\n  .options((req, res) =\u003e console.log('This is an options request')) // Only for OPTIONS requests\n\n  // Default returned responses\n  .get('/', () =\u003e 'Welcome to micro')\n\n  // Parametrized paths\n  .get('/hello/:world', (req, res) =\u003e ({\n    message: `Hello ${req.params.world}`\n  }))\n\n  // Sequenced middlewares no need to use next callback,\n  // All middlewares are processed as async\n  // The first returned response will be sent to the client\n  .get('/hello/:world/whats/:up', [\n    (req, res) =\u003e {\n      res.locals = {};\n      res.locals.response = {\n        message: `Hello ${req.params.world} whats ${req.params.up}`\n      };\n    },\n    (req, res) =\u003e {\n      return res.locals.response;\n    }\n  ])\n\n  // Default parsed body for all methods other than get\n  // Based on the Content-Type parses json, formurlencoded, text and and buffer\n  .post('/hello', () =\u003e req.body)\n\n  // Default parsed query parameters\n  // if you call /hello/with/query/params?hello=world\n  // then req.query = {hello: \"world\"}\n  .get('/hello/with/query/params', () =\u003e req.query)\n\n  // Mix single and array of middlewares\n  .get(\n    '/mixed',\n    (req, res) =\u003e console.log('Middleware 1'),\n    [\n      (req, res) =\u003e console.log('Middleware 1.1'),\n      (req, res) =\u003e console.log('Middleware 1.2'),\n      [\n        (req, res) =\u003e console.log('Middleware 1.2.1'),\n        (req, res) =\u003e console.log('Middleware 1.2.2')\n      ]\n    ],\n    (req, res) =\u003e console.log('Middleware 2'),\n    (req, res) =\u003e 'This is the final response'\n  )\n\n  .use(() =\u003e 'Not found');\n\n// Init micro server\nlet server = micro(router);\n\nserver.listen(3000, () =\u003e console.log('Micro listening on port 3000'));\n```\n\n## Use of subrouters\n\n```javascript\nlet micro = require('micro');\nlet Router = require('micro-ex-router');\n\n// Create a sub router\nlet subrouter = Router();\nsubrouter\n  .use((req, res) =\u003e console.log('Sub router \"Use\" middleware'))\n  .get(\n    '/from/:country',\n    (req, res) =\u003e `Hello ${req.params.world} from ${req.params.country}`\n  );\n\n// Create a new router\nlet router = Router();\nrouter\n  .use((req, res) =\u003e console.log(`${req.url}`))\n  .use('/hello/:world', subrouter)\n  .use(() =\u003e 'Not found');\n\n// Init micro server\nlet server = micro(router);\n\nserver.listen(3000, async () =\u003e console.log('Micro listening on port 3000'));\n```\n\n## Use of Compression, CORS and other NodeJs Middlewares\n\n```javascript\nlet micro = require('micro');\nlet Router = require('micro-ex-router');\nlet compression = require('compression');\nlet cors = require('cors');\n\n// Create a new router\nlet router = Router();\n\nrouter\n  // Add cors middleware\n  .use((req, res) =\u003e new Promise((next) =\u003e cors()(req, res, next)))\n\n  // its the same as\n  // .use((req, res) =\u003e new Promise(resolve =\u003e cors()(req, res, resolve)))\n\n  // Add compression middleware\n  .use((req, res) =\u003e new Promise((next) =\u003e compression()(req, res, next)))\n\n  .get('/', () =\u003e 'Welcome to micro');\n\n// Init micro server\nlet server = micro(router);\n\nserver.listen(3000, () =\u003e console.log('Micro listening on port 3000'));\n```\n\n## Use of Express middlewares\n\n```javascript\nlet micro = require('micro');\nlet Router = require('micro-ex-router');\n\n/**\n * Load and configure the express winston middleware\n */\nlet transports = require('winston').transports;\nlet expressWinston = require('express-winston');\nlet loggerOptions = {\n  transports: [new transports.Console({ colorize: true })],\n  meta: false,\n  msg: '{{res.statusCode}} {{req.method}} {{req.url}} {{res.responseTime}}ms',\n  colorStatus: true\n};\n\n// Create a new router\nlet router = Router();\n\nrouter\n  // Add expressWinston middleware\n  .use(\n    (req, res) =\u003e\n      new Promise((next) =\u003e\n        expressWinston.logger(loggerOptions)(req, res, next)\n      )\n  )\n\n  .get('/', () =\u003e 'Welcome to micro');\n\n// Init micro server\nlet server = micro(router);\n\nserver.listen(3000, () =\u003e console.log('Micro listening on port 3000'));\n```\n\n-   Note that not all express plugins will work with this router. Express modify the request object adding more properties that other plugins may use. So, if the plugin use this properties then it will not work with `micro-ex-router`.\n\n## Serve files from a directory and render a string as html\n\n```javascript\nlet micro = require('micro');\nlet Router = require('micro-ex-router');\n\n// Create a new router\nlet router = Router();\n\n// To render with this headers\nlet htmlWithHeaders = {\n  'Cache-Control': 'public, max-age=2592000',\n  Expires: new Date(Date.now() + 604800000).toUTCString()\n};\n\nlet defaultHeaders = {\n  any: {\n    'Cache-Control': 'no-cache'\n  },\n  css: {\n    'Cache-Control': 'public, max-age=2592000',\n    Expires: new Date(Date.now() + 604800000).toUTCString()\n  }\n};\n\nlet refreshFileListTime = 1000 * 60 * 60; // 60 minutes\n\nrouter\n  // Serve files from a directory\n  .use(Router.serveDir('./public', defaultHeaders, refreshFileListTime))\n  // Serve a single file\n  .get('/file/:file', (req, res) =\u003e\n    Router.serveFile(res, `./public/${req.params.file}`, defaultHeaders)\n  )\n  // Serve a string as html\n  .get('/render/html', Router.render('\u003chtml\u003e\u003cbody\u003eHello world\u003c/body\u003e\u003c/html\u003e'))\n  // Serve a string as html returned by a function\n  .get(\n    '/render/function',\n    Router.render(() =\u003e '\u003chtml\u003e\u003cbody\u003eHello world\u003c/body\u003e\u003c/html\u003e')\n  )\n  // Serve a string as html with custom headers\n  .get(\n    '/render/function',\n    Router.render(() =\u003e '\u003chtml\u003e\u003cbody\u003eHello world\u003c/body\u003e\u003c/html\u003e', htmlWithHeaders)\n  )\n  .use(() =\u003e 'Not found');\n\n// Init micro server\nlet server = micro(router);\n\nserver.listen(3000, () =\u003e console.log('Micro listening on port 3000'));\n```\n\n## Available methods\n\n-   Get\n-   Post\n-   Put\n-   Patch\n-   Delete\n-   Head\n-   Options\n\n## Parsed body and query by default\n\nBased on the Content-Type header, the router will try to parse the body.\n\n-   If type === 'application/json' then parse the body as json\n-   If type === 'application/x-www-form-urlencoded' then parse the body as form urlencoded\n-   If type === 'text/html' then parse the body as text\n-   If other type than the previous ones parse the body as buffer\n\nIf it receive query params, these params will be parsed and will be available on the `req.query` property\n\n## Tests\n\n`npm test`\n\n## Contributing\n\n-   Use prettify and eslint to lint your code.\n-   Add tests for any new or changed functionality.\n-   Update the readme with an example if you add or change any functionality.\n\n## Legal\n\nAuthor: [Masquerade Circus](http://masquerade-circus.net). License [Apache-2.0](https://opensource.org/licenses/Apache-2.0)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMasquerade-Circus%2Fmicro-ex-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FMasquerade-Circus%2Fmicro-ex-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMasquerade-Circus%2Fmicro-ex-router/lists"}