Status: Stable
Note: We recommend using @now/node to best leverage Node.js in a serverless environment. This Builder is production-ready but should only be used by advanced users.

This Builder takes any Node.js HTTP server and wraps it inside a lambda.

When to Use It

To best take advantage of the granularity of serverless, we recommend focusing on exposing function entrypoints to your APIs.

However, to ease the upgrade process to Now 2.0, porting over old non-serverless applications or testing out the system with an existing app, we created and maintain @node/node-server.

How to Use It

Point @now/node-server to a file that opens a HTTP server that listens on a port.

In this example, we will set up an Express.js application and a vanilla HTTP server.

First, we will create two directories inside my-project

mkdir -p my-project/{node-http,express}

We will ensure node_modules are ignored with .nowignore:

node_modules

Inside express, we will set up and install a basic express server:

yarn add express

And express/index.js as follows:

const app = require('express')()
app.get('*', (req, res) => {
  res.send('Hello from Express.js!')
})
app.listen()

Notice that listen does not receive a port, which means it can listen on an ephemeral port. @now/node-server works with any port you listen on.

We will do the same with node-http/index.js:

require('http')
  .createServer((req, res) => {
    res.end('Hello from a vanilla server!')
  })
  .listen()

Finally we will configure a now.json that builds our directories concurrently to turn them into Lambdas that can be invoked on demand:

{
  "version": 2,
  "builds": [{ "src": "*/index.js", "use": "@now/node-server" }]
}

As a result, our deployment will have two routes:

  • /express
  • /node-http

You can check them out live here: https://my-express-project-pugp5a7l8.now.sh/

Technical Details

Entrypoint

The entrypoint is always a single file that when loaded via require opens a single HTTP server port where the main application listens.

Dependencies installation

The installation algorithm of dependencies works as follows:

  • If a package-lock.json is present, npm install is used
  • Otherwise, yarn is used.

Private npm modules

To install private npm modules, define NPM_TOKEN as a build environment variable in now.json.

Node.js version

The Node.js version used is the v8.10.

Maximum Lambda Bundle Size

To help keep cold boot times low, the maximum output bundle size for a Node.js Server lambda is, by default, 15mb. This limit is extendable up to 50mb.

Example maxLambdaSize configuration:
{
  "builds": [
    { "src": "*/index.js", "use": "@now/node-server", "config": { "maxLambdaSize": "20mb" } }
  ]
}