Micro

Asynchronous HTTP microservices

README


Micro — Asynchronous HTTP microservices


Features


Easy: Designed for usage with asyncand await
Fast: Ultra-high performance (even JSON parsing is opt-in)
Micro: The whole project is ~260 lines of code
Agile: Super easy deployment and containerization
Simple: Oriented for single purpose modules (function)
Standard: Just HTTP!
Explicit: No middleware - modules declare all dependencies
Lightweight: With all dependencies, the package weighs less than a megabyte

Disclaimer:Micro was created for use within containers and is not intended for use in serverless environments. For those using Vercel, this means that there is no requirement to use Micro in your projects as the benefits it provides are not applicable to the platform. Utility features provided by Micro, such as json, are readily available in the form of Serverless Function helpers .

Installation


Important:Micro is only meant to be used in production. In development, you should use micro-dev , which provides you with a tool belt specifically tailored for developing microservices.

To prepare your microservice for running in the production environment, firstly install micro:

  1. ``` shell
  2. npm install --save micro
  3. ```

Usage


Create an index.jsfile and export a function that accepts the standard http.IncomingMessage and http.ServerResponse objects:

  1. ``` js
  2. module.exports = (req, res) => {
  3.   res.end('Welcome to Micro');
  4. };
  5. ```

Micro provides useful helpers but also handles return values – so you can write it even shorter!

  1. ``` js
  2. module.exports = () => 'Welcome to Micro';
  3. ```

Next, ensure that the mainproperty inside package.jsonpoints to your microservice (which is inside index.jsin this example case) and add a startscript:

  1. ``` json
  2. {
  3.   "main": "index.js",
  4.   "scripts": {
  5.     "start": "micro"
  6.   }
  7. }
  8. ```

Once all of that is done, the server can be started like this:

  1. ``` shell
  2. npm start
  3. ```

And go to this URL: http://localhost:3000- 🎉

Command line


  1. ``` null
  2.   micro - Asynchronous HTTP microservices

  3.   USAGE

  4.       $ micro --help
  5.       $ micro --version
  6.       $ micro [-l listen_uri [-l ...]] [entry_point.js]

  7.       By default micro will listen on 0.0.0.0:3000 and will look first
  8.       for the "main" property in package.json and subsequently for index.js
  9.       as the default entry_point.

  10.       Specifying a single --listen argument will overwrite the default, not supplement it.

  11.   OPTIONS

  12.       --help                              shows this help message

  13.       -v, --version                       displays the current version of micro

  14.       -l, --listen listen_uri             specify a URI endpoint on which to listen (see below) -
  15.                                           more than one may be specified to listen in multiple places

  16.   ENDPOINTS

  17.       Listen endpoints (specified by the --listen or -l options above) instruct micro
  18.       to listen on one or more interfaces/ports, UNIX domain sockets, or Windows named pipes.

  19.       For TCP (traditional host/port) endpoints:

  20.           $ micro -l tcp://hostname:1234

  21.       For UNIX domain socket endpoints:

  22.           $ micro -l unix:/path/to/socket.sock

  23.       For Windows named pipe endpoints:

  24.           $ micro -l pipe:\\.\pipe\PipeName

  25. ```

async& await


Examples
Fetch external api

Micro is built for usage with async/await.

  1. ``` js
  2. const sleep = require('then-sleep');

  3. module.exports = async (req, res) => {
  4.   await sleep(500);
  5.   return 'Ready!';
  6. };
  7. ```

Port Based on Environment Variable


When you want to set the port using an environment variable you can use:

  1. ``` null
  2. micro -l tcp://0.0.0.0:$PORT

  3. ```

Optionally you can add a default if it suits your use case:

  1. ``` null
  2. micro -l tcp://0.0.0.0:${PORT-3000}

  3. ```

${PORT-3000}will allow a fallback to port 3000when $PORTis not defined.

Note that this only works in Bash.

Body parsing


Examples
Parse JSON
Parse urlencoded form (html form tag)

For parsing the incoming request body we included an async functions buffer, textand json

  1. ``` js
  2. const { buffer, text, json } = require('micro');

  3. module.exports = async (req, res) => {
  4.   const buf = await buffer(req);
  5.   console.log(buf);
  6.   //
  7.   const txt = await text(req);
  8.   console.log(txt);
  9.   // '{"price": 9.99}'
  10.   const js = await json(req);
  11.   console.log(js.price);
  12.   // 9.99
  13.   return '';
  14. };
  15. ```

API


buffer(req, { limit = '1mb', encoding = 'utf8' })

text(req, { limit = '1mb', encoding = 'utf8' })

json(req, { limit = '1mb', encoding = 'utf8' })

Buffers and parses the incoming body and returns it.
Exposes an asyncfunction that can be run with await.
Can be called multiple times, as it caches the raw request body the first time.
limitis how much data is aggregated before parsing at max. Otherwise, an Erroris thrown with statusCodeset to 413(see Error Handling ). It can be aNumberof bytes or a string like'1mb'.
If JSON parsing fails, an Erroris thrown with statusCodeset to 400(see Error Handling )

For other types of data check the examples

Sending a different status code


So far we have used returnto send data to the client. return 'Hello World'is the equivalent of send(res, 200, 'Hello World').

  1. ``` js
  2. const { send } = require('micro');

  3. module.exports = async (req, res) => {
  4.   const statusCode = 400;
  5.   const data = { error: 'Custom error message' };

  6.   send(res, statusCode, data);
  7. };
  8. ```

send(res, statusCode, data = null)

Use require('micro').send.
statusCodeis a Numberwith the HTTP status code, and must always be supplied.
If datais supplied it is sent in the response. Different input types are processed appropriately, and Content-Typeand Content-Lengthare automatically set.
Stream: datais piped as an octet-stream. Note: it is yourresponsibility to handle the errorevent in this case (usually, simply logging the error and aborting the response is enough).
Buffer: datais written as an octet-stream.
object: datais serialized as JSON.
string: datais written as-is.

If JSON serialization fails (for example, if a cyclical reference is found), a 400error is thrown. See Error Handling .

Programmatic use


You can use Micro programmatically by requiring Micro directly:

  1. ``` js
  2. const http = require('http');
  3. const serve = require('micro');
  4. const sleep = require('then-sleep');

  5. const server = new http.Server(
  6.   serve(async (req, res) => {
  7.     await sleep(500);
  8.     return 'Hello world';
  9.   }),
  10. );

  11. server.listen(3000);
  12. ```

serve(fn)

Use require('micro').serve.
Returns a function with the (req, res) => voidsignature. That uses the provided functionas the request handler.
The supplied function is run with await. So it can be async

sendError(req, res, error)

Use require('micro').sendError.
Used as the default handler for errors thrown.
Automatically sets the status code of the response based on error.statusCode.
Sends the error.messageas the body.
Stacks are printed out with console.errorand during development (when NODE_ENVis set to 'development') also sent in responses.
Usually, you don't need to invoke this method yourself, as you can use the built-in error handling flow withthrow.

createError(code, msg, orig)

Use require('micro').createError.
Creates an error object with a statusCode.
Useful for easily throwing errors with HTTP status codes, which are interpreted by the built-in error handling .
origsets error.originalErrorwhich identifies the original error (if any).

Error Handling


Micro allows you to write robust microservices. This is accomplished primarily by bringing sanity back to error handling and avoiding callback soup.

If an error is thrown and not caught by you, the response will automatically be 500. Important:Error stacks will be printed as console.errorand during development mode (if the env variable NODE_ENVis 'development'), they will also be included in the responses.

If the Errorobject that's thrown contains a statusCodeproperty, that's used as the HTTP code to be sent. Let's say you want to write a rate limiting module:

  1. ``` js
  2. const rateLimit = require('my-rate-limit');

  3. module.exports = async (req, res) => {
  4.   await rateLimit(req);
  5.   // ... your code
  6. };
  7. ```

If the API endpoint is abused, it can throw an error with createErrorlike so:

  1. ``` js
  2. if (tooMany) {
  3.   throw createError(429, 'Rate limit exceeded');
  4. }
  5. ```

Alternatively you can create the Errorobject yourself

  1. ``` js
  2. if (tooMany) {
  3.   const err = new Error('Rate limit exceeded');
  4.   err.statusCode = 429;
  5.   throw err;
  6. }
  7. ```

The nice thing about this model is that the statusCodeis merely a suggestion. The user can override it:

  1. ``` js
  2. try {
  3.   await rateLimit(req);
  4. } catch (err) {
  5.   if (429 == err.statusCode) {
  6.     // perhaps send 500 instead?
  7.     send(res, 500);
  8.   }
  9. }
  10. ```

If the error is based on another error that Microcaught, like a JSON.parseexception, then originalErrorwill point to it. If a generic error is caught, the status will be set to 500.

In order to set up your own error handling mechanism, you can use composition in your handler:

  1. ``` js
  2. const { send } = require('micro');

  3. const handleErrors = (fn) => async (req, res) => {
  4.   try {
  5.     return await fn(req, res);
  6.   } catch (err) {
  7.     console.log(err.stack);
  8.     send(res, 500, 'My custom error!');
  9.   }
  10. };

  11. module.exports = handleErrors(async (req, res) => {
  12.   throw new Error('What happened here?');
  13. });
  14. ```

Testing


Micro makes tests compact and a pleasure to read and write. We recommend Node TAP or AVA , a highly parallel test framework with built-in support for async tests:

  1. ``` js
  2. const http = require('http');
  3. const { send, serve } = require('micro');
  4. const test = require('ava');
  5. const listen = require('test-listen');
  6. const fetch = require('node-fetch');

  7. test('my endpoint', async (t) => {
  8.   const service = new http.Server(
  9.     serve(async (req, res) => {
  10.       send(res, 200, {
  11.         test: 'woot',
  12.       });
  13.     }),
  14.   );

  15.   const url = await listen(service);
  16.   const response = await fetch(url);
  17.   const body = await response.json();

  18.   t.deepEqual(body.test, 'woot');
  19.   service.close();
  20. });
  21. ```

Look at test-listen for a function that returns a URL with an ephemeral port every time it's called.

Contributing


Fork this repository to your own GitHub account and then clone it to your local device
Link the package to the global module directory: npm link
Within the module you want to test your local development instance of Micro, just link it to the dependencies: npm link micro. Instead of the default one from npm, node will now use your clone of Micro!

You can run the tests using: npm test.

Credits


Thanks to Tom Yandell and Richard Hodgson for donating the name "micro" on npm !

Authors


Guillermo Rauch (@rauchg ) - Vercel
Leo Lamprecht (@notquiteleo ) - Vercel
Tim Neutkens (@timneutkens ) - Vercel