Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
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 — Asynchronous HTTP microservices
async
and await
(more)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
Then create an index.js
file and populate it with function, that accepts 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
- 🎉
async
& await
Micro is built for usage with async/await. You can read more about async / await here
const sleep = require('then-sleep')
module.exports = async (req, res) => {
await sleep(500)
return 'Ready!'
}
The package takes advantage of native support for async
and await
, which is always as of Node.js 8.0.0! In turn, we suggest either using at least this version both in development and production (if possible), or transpiling the code using async-to-gen, if you can't use the latest Node.js version.
In order to do that, you firstly need to install it:
npm install -g async-to-gen
And then add the transpilation command to the scripts.build
property inside package.json
:
{
"scripts": {
"build": "async-to-gen input.js > output.js"
}
}
Once these two steps are done, you can transpile the code by running this command:
npm run build
That's all it takes to transpile by yourself. But just to be clear: Only do this if you can't use Node.js 8.0.0! If you can, async
and await
will just work right out of the box.
When you want to set the port using an environment variable you can use:
micro -p $PORT
Optionally you can add a default if it suits your use case:
micro -p ${PORT:-3000}
${PORT:-3000}
will allow a fallback to port 3000
when $PORT
is not defined.
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 ''
}
buffer(req, { limit = '1mb', encoding = 'utf8' })
text(req, { limit = '1mb', encoding = 'utf8' })
json(req, { limit = '1mb', encoding = 'utf8' })
async
function that can be run with await
.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'
.Error
is thrown with statusCode
set to 400
(see Error Handling)For other types of data check the examples
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)
require('micro').send
.statusCode
is a Number
with the HTTP status code, and must always be supplied.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.400
error is thrown. See Error Handling.You can use Micro programmatically by requiring Micro directly:
const micro = require('micro')
const sleep = require('then-sleep')
const server = micro(async (req, res) => {
await sleep(500)
return 'Hello world'
})
server.listen(3000)
default
export.require('micro')
.http.Server
that uses the provided function
as the request handler.await
. So it can be async
require('micro').sendError
.error.statusCode
.error.message
as the body.console.error
and during development (when NODE_ENV
is set to 'development'
) also sent in responses.throw
.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: 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?')
})
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 (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')
service.close()
})
Look at test-listen for a function that returns a URL with an ephemeral port every time it's called.
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 to Tom Yandell and Richard Hodgson for donating the name "micro" on npm!
FAQs
Asynchronous HTTP microservices
The npm package micro receives a total of 491,253 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.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.