Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
The 'micro' npm package is a minimalistic framework for creating HTTP microservices. It is designed to be simple, fast, and lightweight, making it ideal for building small, focused services that can be deployed independently.
Basic HTTP Server
This code demonstrates how to create a basic HTTP server using 'micro'. The server listens on port 3000 and responds with 'Hello, world!' to any incoming request.
const { send } = require('micro');
const http = require('http');
const server = http.createServer((req, res) => send(res, 200, 'Hello, world!'));
server.listen(3000, () => console.log('Server running on port 3000'));
Handling JSON Requests
This example shows how to handle JSON requests with 'micro'. The server reads the JSON body of the incoming request and responds with the same data wrapped in an object.
const { json, send } = require('micro');
module.exports = async (req, res) => {
const data = await json(req);
send(res, 200, { received: data });
};
Routing with micro-router
This code demonstrates how to use 'microrouter' with 'micro' to handle routing. It defines routes for GET and POST requests to '/hello' and a catch-all route for 404 Not Found responses.
const { send } = require('micro');
const { router, get, post } = require('microrouter');
const hello = (req, res) => send(res, 200, 'Hello, world!');
const notFound = (req, res) => send(res, 404, 'Not Found');
module.exports = router(
get('/hello', hello),
post('/hello', hello),
get('/*', notFound)
);
Express is a widely-used web application framework for Node.js. It provides a robust set of features for building web and mobile applications, including routing, middleware support, and template engines. Compared to 'micro', Express is more feature-rich and suitable for larger applications.
Koa is a next-generation web framework for Node.js created by the team behind Express. It uses async functions to simplify middleware and improve error handling. Koa is more modular and lightweight compared to Express, but still more feature-rich than 'micro'.
Hapi is a rich framework for building applications and services. It is known for its powerful plugin system and configuration-based approach. Hapi is more opinionated and feature-complete compared to 'micro', making it suitable for complex applications.
Micro — Async ES6 HTTP microservices
async
and await
(more)async
transpilation fast and transparentThe following example sleep.js
will wait before responding (without blocking!)
const {send} = require('micro')
const sleep = require('then-sleep')
module.exports = async function (req, res) {
await sleep(500)
send(res, 200, 'Ready!')
}
To run the microservice on port 3000
, use the micro
command:
micro sleep.js
To run the microservice on port 3000
and localhost instead of listening on every interface, use the micro
command:
micro -H localhost sleep.js
Install the package (requires at least Node v6):
npm install --save micro
And start using it in your package.json
file:
"main": "index.js",
"scripts": {
"start": "micro"
}
Then write your index.js
(see above for an example).
After that, you can make the server run by executing the following command:
npm start
micro(fn)
This function is exposed as the default
export.
Use require('micro')
.
Returns a http.Server
that uses the provided fn
as the request handler.
The supplied function is run with await
. It can be async
!
Example:
const micro = require('micro');
const sleep = require('then-sleep');
const srv = micro(async function (req, res) {
await sleep(500);
res.writeHead(200);
res.end('woot');
});
srv.listen(3000);
json(req, { limit = '1mb' })
Use require('micro').json
.
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)
Example:
const { json, send } = require('micro');
module.exports = async function (req, res) {
const data = await json(req);
console.log(data.price);
send(res, 200);
}
send(res, statusCode, data = null)
Use require('micro').send
.
statusCode
is a Number
with the HTTP error 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.
Example
const { send } = require('micro')
module.exports = async function (req, res) {
send(res, 400, { error: 'Please use a valid email' });
}
return val;
Returning val
from your function is shorthand for: send(res, 200, val)
.
Example
module.exports = function (req, res) {
return {message: 'Hello!'};
}
Returning a promise works as well!
Example
const sleep = require('then-sleep')
module.exports = async function (req, res) {
return new Promise(async (resolve) => {
await sleep(100);
resolve('I Promised');
});
}
sendError(req, res, error)
require('micro').sendError
.error.statusCode
.error.message
as the body.NODE_ENV
is set to 'development'
), stacks are printed out with console.error
and also sent in responses.throw
.createError(code, msg, orig)
require('micro').createError
.statusCode
.orig
sets error.originalError
which identifies the original error (if any).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: during development mode (if the env variable NODE_ENV
is 'development'
), error stacks will be printed as console.error
and 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 function (req, res) {
await rateLimit(req);
// … your code
}
If the API endpoint is abused, it can throw an error like so:
if (tooMany) {
const err = new Error('Rate limit exceeded');
err.statusCode = 429;
throw err;
}
Alternatively you can use createError
as described above.
if (tooMany) {
throw createError(429, 'Rate limit exceeded')
}
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:
module.exports = handleErrors(async (req, res) => {
throw new Error('What happened here?');
});
function handleErrors (fn) {
return async function (req, res) {
try {
return await fn(req, res);
} catch (err) {
console.log(err.stack);
send(res, 500, 'My custom error!');
}
}
}
Micro makes tests compact and a pleasure to read and write. We recommend ava, a highly parallel micro test framework with built-in support for async tests:
const micro = require('micro');
const test = require('ava');
const listen = require('test-listen');
const request = require('request-promise');
test('my endpoint', async t => {
const service = micro(async function (req, res) {
micro.send(res, 200, { test: 'woot' })
});
const url = await listen(service);
const body = await request(url);
t.deepEqual(JSON.parse(body).test, 'woot');
});
Look at the test-listen for a function that returns a URL with an ephemeral port every time it's called.
We use is-async-supported combined with async-to-gen,
so that the we only convert async
and await
to generators when needed.
If you want to do it manually, you can! micro(1)
is idempotent and
should not interfere.
micro
exclusively supports Node 6+ to avoid a big transpilation
pipeline. async-to-gen
is fast and can be distributed with
the main micro
package due to its small size.
You can use the micro
CLI for npm start
:
{
"name": "my-microservice",
"dependencies": {
"micro": "x.y.z"
},
"main": "microservice.js",
"scripts": {
"start": "micro -p 3000"
}
}
Then simply run npm start
!
npm link
npm start
npm link micro
. Instead of the default one from npm, node will now use your clone of micro!As always, you can run the AVA and ESLint tests using: npm test
Thanks Tom Yandell and Richard Hodgson for donating the micro
npm name.
FAQs
Asynchronous HTTP microservices
The npm package micro receives a total of 264,843 weekly downloads. As such, micro popularity was classified as popular.
We found that micro demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.