• Stars
    star
    10,525
  • Rank 3,086 (Top 0.07 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Asynchronous HTTP microservices

Micro β€” Asynchronous HTTP microservices

Features

  • Easy: Designed for usage with async and 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:

npm install --save micro

Usage

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

module.exports = (req, res) => {
  res.end('Welcome to Micro');
};

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

module.exports = () => 'Welcome to Micro';

Next, ensure that the main property inside package.json points to your microservice (which is inside index.js in this example case) and add a start script:

{
  "main": "index.js",
  "scripts": {
    "start": "micro"
  }
}

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

npm start

And go to this URL: http://localhost:3000 - πŸŽ‰

Command line

  micro - Asynchronous HTTP microservices

  USAGE

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

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

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

  OPTIONS

      --help                              shows this help message

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

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

  ENDPOINTS

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

      For TCP (traditional host/port) endpoints:

          $ micro -l tcp://hostname:1234

      For UNIX domain socket endpoints:

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

      For Windows named pipe endpoints:

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

async & await

Examples

Micro is built for usage with async/await.

const sleep = require('then-sleep');

module.exports = async (req, res) => {
  await sleep(500);
  return 'Ready!';
};

Port Based on Environment Variable

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

micro -l tcp://0.0.0.0:$PORT

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

micro -l tcp://0.0.0.0:${PORT-3000}

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

Note that this only works in Bash.

Body parsing

Examples

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

const { buffer, text, json } = require('micro');

module.exports = async (req, res) => {
  const buf = await buffer(req);
  console.log(buf);
  // <Buffer 7b 22 70 72 69 63 65 22 3a 20 39 2e 39 39 7d>
  const txt = await text(req);
  console.log(txt);
  // '{"price": 9.99}'
  const js = await json(req);
  console.log(js.price);
  // 9.99
  return '';
};

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 async function that can be run with await.
  • Can be called multiple times, as it caches the raw request body the first time.
  • limit is how much data is aggregated before parsing at max. Otherwise, an Error is thrown with statusCode set to 413 (see Error Handling). It can be a Number of bytes or a string like '1mb'.
  • If JSON parsing fails, an Error is thrown with statusCode set to 400 (see Error Handling)

For other types of data check the examples

Sending a different status code

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

const { send } = require('micro');

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

  send(res, statusCode, data);
};
send(res, statusCode, data = null)
  • Use require('micro').send.
  • statusCode is a Number with the HTTP status code, and must always be supplied.
  • If data is supplied it is sent in the response. Different input types are processed appropriately, and Content-Type and Content-Length are automatically set.
    • Stream: data is piped as an octet-stream. Note: it is your responsibility to handle the error event in this case (usually, simply logging the error and aborting the response is enough).
    • Buffer: data is written as an octet-stream.
    • object: data is serialized as JSON.
    • string: data is written as-is.
  • If JSON serialization fails (for example, if a cyclical reference is found), a 400 error is thrown. See Error Handling.

Programmatic use

You can use Micro programmatically by requiring Micro directly:

const http = require('http');
const sleep = require('then-sleep');
const { serve } = require('micro');

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

server.listen(3000);
serve(fn)
  • Use require('micro').serve.
  • Returns a function with the (req, res) => void signature. That uses the provided function as 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.message as the body.
  • Stacks are printed out with console.error and during development (when NODE_ENV is 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 with throw.
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.
  • orig sets error.originalError which 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.error and during development mode (if the env variable NODE_ENV is 'development'), they will also be included in the responses.

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

const rateLimit = require('my-rate-limit');

module.exports = async (req, res) => {
  await rateLimit(req);
  // ... your code
};

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

if (tooMany) {
  throw createError(429, 'Rate limit exceeded');
}

Alternatively you can create the Error object yourself

if (tooMany) {
  const err = new Error('Rate limit exceeded');
  err.statusCode = 429;
  throw err;
}

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

try {
  await rateLimit(req);
} catch (err) {
  if (429 == err.statusCode) {
    // perhaps send 500 instead?
    send(res, 500);
  }
}

If the error is based on another error that Micro caught, like a JSON.parse exception, then originalError will 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:

const { send } = require('micro');

const handleErrors = (fn) => async (req, res) => {
  try {
    return await fn(req, res);
  } catch (err) {
    console.log(err.stack);
    send(res, 500, 'My custom error!');
  }
};

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

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:

const http = require('http');
const { send, serve } = require('micro');
const test = require('ava');
const listen = require('test-listen');
const fetch = require('node-fetch');

test('my endpoint', async (t) => {
  const service = new http.Server(
    serve(async (req, res) => {
      send(res, 200, {
        test: 'woot',
      });
    }),
  );

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

  t.deepEqual(body.test, 'woot');
  service.close();
});

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

Contributing

  1. Fork this repository to your own GitHub account and then clone it to your local device
  2. Link the package to the global module directory: npm link
  3. 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

More Repositories

1

next.js

The React Framework
JavaScript
120,483
star
2

hyper

A terminal built on web technologies
TypeScript
42,467
star
3

swr

React Hooks for Data Fetching
TypeScript
29,423
star
4

turbo

Incremental bundler and build system optimized for JavaScriptΒ and TypeScript, written in Rust – including Turbopack and Turborepo.
Rust
24,396
star
5

pkg

Package your Node.js project into an executable
JavaScript
24,151
star
6

vercel

Develop. Preview. Ship.
TypeScript
11,950
star
7

commerce

Next.js Commerce
TypeScript
10,203
star
8

satori

Enlightened library to convert HTML and CSS to SVG
TypeScript
10,131
star
9

serve

Static file serving and directory listing
TypeScript
9,088
star
10

ncc

Compile a Node.js project into a single file. Supports TypeScript, binary addons, dynamic requires.
JavaScript
8,786
star
11

ai

Build AI-powered applications with React, Svelte, Vue, and Solid
TypeScript
7,728
star
12

styled-jsx

Full CSS support for JSX without compromises
JavaScript
7,577
star
13

nextjs-subscription-payments

Clone, deploy, and fully customize a SaaS subscription application with Next.js.
TypeScript
5,334
star
14

platforms

A full-stack Next.js app with multi-tenancy and custom domain support. Built with Next.js App Router and the Vercel Domains API.
TypeScript
5,193
star
15

ms

Tiny millisecond conversion utility
TypeScript
4,912
star
16

ai-chatbot

A full-featured, hackable Next.js AI chatbot built by Vercel
TypeScript
4,894
star
17

og-image

Open Graph Image as a Service - generate cards for Twitter, Facebook, Slack, etc
TypeScript
4,031
star
18

release

Generate changelogs with a single command
JavaScript
3,544
star
19

examples

Enjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications.
TypeScript
3,288
star
20

next-learn

Learn Next.js Starter Code
TypeScript
3,181
star
21

hazel

Lightweight update server for Electron apps
JavaScript
2,855
star
22

next-plugins

Official Next.js plugins
2,676
star
23

app-playground

https://app-dir.vercel.app/
TypeScript
2,260
star
24

virtual-event-starter-kit

Open source demo that Next.js developers can clone, deploy, and fully customize for events.
TypeScript
2,115
star
25

geist-font

1,846
star
26

async-retry

Retrying made simple, easy and async
JavaScript
1,780
star
27

arg

Simple argument parsing
JavaScript
1,191
star
28

react-tweet

Embed tweets in your React application.
TypeScript
1,188
star
29

nft

Node.js dependency tracing utility
JavaScript
1,182
star
30

avatar

πŸ’Ž Beautiful avatars as a microservice
TypeScript
1,065
star
31

style-guide

Vercel's engineering style guide
JavaScript
1,064
star
32

next-react-server-components

Demo repository for Next.js + React Server Components
JavaScript
962
star
33

nextjs-postgres-auth-starter

Next.js + Tailwind + Typescript + Drizzle + NextAuth + PostgreSQL starter template.
TypeScript
817
star
34

nextjs-postgres-nextauth-tailwindcss-template

Admin dashboard template.
TypeScript
797
star
35

edge-runtime

Developing, testing, and defining the runtime Web APIs for Edge infrastructure.
TypeScript
736
star
36

server-components-notes-demo

Experimental demo of React Server Components with Next.js. Deployed serverlessly on Vercel.
TypeScript
723
star
37

micro-dev

The development environment for `micro`
JavaScript
695
star
38

nextgram

A sample Next.js app showing dynamic routing with modals as a route.
TypeScript
681
star
39

nextjs-portfolio-starter

Easily create a portfolio with Next.js and Markdown.
JavaScript
635
star
40

react-keyframes

Create frame-based animations in React
TypeScript
615
star
41

hyperpower

Hyper particle effects extension
JavaScript
613
star
42

static-fun

A fun demo for wildcard domains
TypeScript
610
star
43

async-sema

Semaphore using `async` and `await`
TypeScript
602
star
44

title

A service for capitalizing your title properly
JavaScript
576
star
45

fetch

Opinionated `fetch` (with retrying and DNS caching) optimized for use with Node.js
JavaScript
564
star
46

serve-handler

The foundation of `serve`
JavaScript
545
star
47

vrs

A serverless virtual reality e-commerce experience powered by Vercel
TypeScript
517
star
48

swr-site

The official website for SWR.
MDX
464
star
49

fun

Ζ’un - Local serverless function Ξ» development runtime
TypeScript
462
star
50

storage

Vercel Postgres, KV, Blob, and Edge Config
TypeScript
455
star
51

mongodb-starter

A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integration.
TypeScript
439
star
52

spr-landing

Serverless Pre-Rendering Landing Page
CSS
426
star
53

hyper-site

The official website for the Hyper terminal
JavaScript
418
star
54

pkg-fetch

A utility to fetch or build patched Node binaries used by `pkg` to generate executables. This repo hosts prebuilt binaries in Releases.
TypeScript
412
star
55

analytics

Privacy-friendly, real-time traffic insights
TypeScript
384
star
56

sveltekit-commerce

SvelteKit Commerce
Svelte
357
star
57

reactions

Next.js Incremental Static Regeneration Demo
JavaScript
308
star
58

email-prompt

CLI email prompt with autocompletion and built-in validation
JavaScript
275
star
59

uid-promise

Creates a cryptographically strong UID
TypeScript
250
star
60

fetch-retry

Wrapper around `fetch` with sensible retrying defaults
JavaScript
220
star
61

git-hooks

No nonsense Git hook management
JavaScript
198
star
62

zsh-theme

Yet another zsh theme
178
star
63

remote-cache

The Vercel Remote Cache SDK
TypeScript
169
star
64

cosmosdb-server

A Cosmos DB server implementation for testing your applications locally.
TypeScript
167
star
65

update-check

Minimalistic update notifications for command line interfaces
JavaScript
157
star
66

test-listen

Quick ephemeral URLs for your tests
JavaScript
153
star
67

install-node

Simple one-liner shell script that installs official Node.js binaries
Shell
136
star
68

terraform-provider-vercel

Terraform Vercel Provider
Go
129
star
69

title-site

A website for capitalizing your titles
JavaScript
123
star
70

preview-mode-demo

This demo showcases Next.js' next-gen Static Site Generation (SSG) support.
TypeScript
105
star
71

nextjs-discord-bot

Discord bot for the official Next.js Discord
TypeScript
100
star
72

beginner-sveltekit

The complete course to start your journey building Svelte applications.
JavaScript
97
star
73

err-sh

Microservice that forwards you to error messages
JavaScript
96
star
74

community

Welcome to the Vercel Community. Discuss feature requests, ask questions, and connect with others in the community.
96
star
75

webpack-asset-relocator-loader

Used in ncc while emitting and relocating any asset references
JavaScript
95
star
76

commerce-framework

TypeScript
94
star
77

hyperyellow

Example theme for hyperterm
JavaScript
87
star
78

schemas

All schemas used for validation that are shared between our projects
JavaScript
78
star
79

nuxt3-kitchen-sink

An example template showing all Nuxt 3 features on Vercel.
Vue
64
star
80

next-codemod

codemod transformations to help upgrade Next.js codebases
JavaScript
63
star
81

react-transition-progress

Show a progress bar while React Transitions run
TypeScript
57
star
82

otel

TypeScript
54
star
83

opentelemetry-collector-dev-setup

Shell
50
star
84

async-listen

Promisify server.listen for your HTTP/HTTPS/TCP server.
TypeScript
45
star
85

wait-for

Small utility that waits for a file to exist and optionally have some permissions set.
C
44
star
86

tracing-js

An implementation of Opentracing API for honeycomb.io
TypeScript
43
star
87

dns-cached-resolve

Caching DNS resolver
TypeScript
40
star
88

example-integration

TypeScript
38
star
89

fetch-cached-dns

A decorator on top of `fetch` that caches the DNS query
JavaScript
35
star
90

speed-insights

Vercel Speed Insights package
TypeScript
30
star
91

remark-capitalize

Transform all markdown titles with title.sh
JavaScript
29
star
92

resolve-node

API endpoint to resolve an arbitrary Node.js version with semver support
JavaScript
29
star
93

cra-to-next

An example of migrating Create React App to Next.js.
JavaScript
24
star
94

ng-deploy-vercel

Deploy Angular applications to Vercel
TypeScript
22
star
95

stripe-integration

A Vercel deploy integration to automatically set up your Stripe API keys and webhook secrets.
TypeScript
21
star
96

rcurl

`curl --resolve` helper script
Shell
21
star
97

release-auth

Handles the authentication for `release`
JavaScript
21
star
98

gatsby-plugin-vercel

Track Core Web Vitals in Gatsby projects with Vercel Analytics.
JavaScript
20
star
99

cert-demo

TypeScript
19
star
100

go-bridge

Bridge for `@vercel/go`
Go
18
star