This post contains content about Now 1.0 – Learn about the latest version, Now 2.0.
Now 2.0 - Upgrade Available
Typically, when writing a micro microservice, you export a function as the request handler:
module.exports = async (req, res) => {
  return 'Hello World'
Next, you run the micro command, which is usually configured as your start script in package.json.
However, many projects have a "setup" step before they can effectively start accepting connections. For example: Setting up a database connection or preloading data.
As of micro 9.1.0, you can export a Promise that resolves to the function that handles your requests:
const setupDatabase = require('some-database')
let database

async function setup(handler) {
  database = await setupDatabase()
  return handler

module.exports = setup((req, res) => {
  return database.get('user')
The moment micro loads the file, the setup function is executed. It waits for the database connection to start and then returns the handler. Once the handler is returned, the HTTP server is started.

Usage with Next.js

Next.js typically requires only a tiny setup: You create a pages directory and run next to get started. However, for advanced use cases it's frequently desirable to set up a custom server that can, for example, handle dynamic routes and caching.
Now you can use micro as your custom Next.js server!
To get started, create a index.js file with the following contents:
const dev = process.env.NODE_ENV !== 'production'
const url = require('url')
const next = require('next')
const app = next({ dev })
const handle = app.getRequestHandler()

async function setup(handler) {
  await app.prepare()
  return handler

module.exports = setup((req, res) => {
  const parsedUrl = url.parse(req.url, true)

  if (parsedUrl.pathname === '/a') {
    return app.render(req, res, '/a', parsedUrl.query)

  return handle(req, res, parsedUrl)
Afterwards, all you have to do to is start the custom server like this:

In Development

When building a microservice, you should be using micro-dev for maximum efficiency. In turn, we also released version 2.2.0, which introduces the same handling for setup scripts as the one that micro provides. The only difference is the command:

Caught a Bug?

Just as you would expect it, both micro and micro-dev are fully open-source. This means that we would be happy to accept any form of contribution of your side, if you're interested in fixing a bug or adding a feature.
In addition to checking out the code, also make sure to join our community if you have any questions.