vercel/micro
Snapshot của vercel/micro: 10.6k★ · TypeScript. Asynchronous HTTP microservices
Tóm tắt dựng từ metadata GitHub của chính dự án — chưa có bài review TopGit. Trang sẽ tự động cập nhật khi bài review đầy đủ được xuất bản.
TopGit viết bài đầy đủ cho repo có nhiều sao nhất và được yêu cầu nhiều nhất. Trang này là snapshot trong thời gian chờ — xem README gốc ở tab READ ME.
Snapshot
Cộng tác viên hàng đầu
Xem cộng tác viên hàng đầu
Micro — Asynchronous HTTP microservices
Features
- Easy: Designed for usage with
asyncandawait - 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
- Fetch external api
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
- Parse JSON
- Parse urlencoded form (html `form` tag)
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
asyncfunction that can be run withawait. - 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, anErroris thrown withstatusCodeset to413(see Error Handling). It can be aNumberof bytes or a string like'1mb'.- If JSON parsing fails, an
Erroris thrown withstatusCodeset to400(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. statusCodeis aNumberwith the HTTP status code, and must always be supplied.- If
datais supplied it is sent in the response. Different input types are processed appropriately, andContent-TypeandContent-Lengthare automatically set.Stream:datais piped as anoctet-stream. Note: it is your responsibility to handle theerrorevent in this case (usually, simply logging the error and aborting the response is enough).Buffer:datais written as anoctet-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:
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) => voidsignature. That uses the providedfunctionas the request handler. - The supplied function is run with
await. So it can beasync
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 (whenNODE_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 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.
origsetserror.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.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
- 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 (@leo) - Vercel
- Tim Neutkens (@timneutkens) - Vercel
Repo liên quan
Master programming by recreating your favorite technologies from scratch.
A curated meta-list of curated lists organized by technology domain. The repository acts as a directory pointing to hundreds of specialized awesome lists covering programming languages, platforms, frameworks, and tooling. All content is community-contributed under the CC0 public domain dedication.
Public APIs is a community-curated GitHub repository listing free, publicly accessible APIs across a wide range of categories, with auth type, HTTPS, and CORS noted for each entry. It's a browsable reference, not a library to install.
REA is an MCP server and CLI that gives AI coding agents the ability to reverse engineer binaries, JavaScript apps, .NET assemblies, and websites. It hooks into Hopper, Ghidra, or IDA Pro for native binary work, or runs static JavaScript analysis with just Node.js. Every investigation returns an Evidence bundle that includes what was found, what was not, and the reasoning path. Setup registers REA with supported agents and walks you through connecting an analysis engine. The CLI also works standalone for terminal-first workflows.
Trả lời nhanh
Đọc thêm về vercel/micro ở đâu?
Trang TopGit này là một snapshot — tab "Readme" hiển thị nguyên văn README của repo (đã bỏ link, giữ ảnh). Repo GitHub ở github.com/vercel/micro là nguồn chính thức.
vercel/micro có phải mã nguồn mở không?
Có — vercel/micro phát hành theo license MIT, nghĩa là mã nguồn mở để đọc, fork và (tùy license) tái sử dụng. Mã: github.com/vercel/micro.
vercel/micro là gì?
vercel/micro (vercel/micro) là dự án TypeScript trên GitHub. Theo mô tả gốc: Asynchronous HTTP microservices
Đọc đầy đủ README ở tab phía trên.
Vẫn đang phân vân về micro?
Một cú bấm sẽ gửi câu hỏi kèm trang này cho AI — xem AI nói gì về micro.