Node.js

Last updated 2nd June 2022

Objective

Node.js is a popular asynchronous JavaScript runtime. Deploy scalable Node.js apps of all sizes on Web PaaS. You can also develop a microservice architecture mixing JavaScript and other apps with multi-app projects.

Supported versions

Grid
6
8
10
12
14
16

To use a specific version in a container with a different language, use a version manager.

Deprecated versions

Grid
0.12
4.7
4.8
6.1
6.9
8.2

Usage example

To use Node.js on Web PaaS and Node.js together, configure the .platform.app.yaml file with a few key settings (a complete example is included at the end).

1. Specify the version

Choose a version from the list above and add it to your app configuration:

type: 'nodejs:16'

2. Specify any global dependencies

Add the following to your app configuration:

location=".platform.app.yaml"
dependencies:
    nodejs:
        yarn: "*"

These are now available as commands, the same as installing with npm install -g.

3. Build your app

Include any commands needed to build and setup your app in the hooks, as in the following example:

location=".platform.app.yaml"
hooks:
    build: |
        npm run setup-assets
        npm run build

4. Start your app

Specify a command to start serving your app (it must be a process running in the foreground):

location=".platform.app.yaml"
web:
    commands:
        start: node index.js

5. Listen on the right port

Make sure your Node.js application is configured to listen over the port given by the environment. The following example uses the platformsh-config helper:

// Load the http module to create an http server.
const http = require('http');

// Load the Web PaaS configuration
const config = require('platformsh-config').config();

const server = http.createServer(function (request, response) {
    response.writeHead(200, {"Content-Type": "application/json"});
    response.end("Hello world!");
});

// Listen on the port from the Web PaaS configuration
server.listen(config.port);

Complete example

A complete basic app configuration looks like the following:

location=".platform.app.yaml"
name: node-app

type: nodejs:16

disk: 512

dependencies:
    nodejs:
        yarn: "*"

hooks:
    build: |
        npm run setup-assets
        npm run build

web:
    commands:
        start: "node index.js"

Dependencies

By default, Web PaaS assumes you're using npm as a package manager. If you have a package.json file in your code, the default build flavor is run:

npm prune --userconfig .npmrc && npm install --userconfig .npmrc

This means you can specify configuration in a .npmrc file in your app root.

Use yarn as a package manager

To switch to yarn to manage dependencies, follow these steps:

Step 1: Switch to a build flavor of none (so packages aren't installed with npm)

location=".platform.app.yaml"
build:
    flavor: none

Step 2: Add yarn as a global dependency

location=".platform.app.yaml"
dependencies:
    nodejs:
        yarn: "1.22.17"

Step 3: Install dependencies in the build hook

location=".platform.app.yaml"
hooks:
    build: |
        yarn --frozen-lockfile

Connecting to services

The following examples show how to use Node.js to access various services. To configure a given service, see the page dedicated to that service.

const elasticsearch = require("elasticsearch");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("elasticsearch");

    const client = new elasticsearch.Client({
        host: `${credentials.host}:${credentials.port}`,
    });

    const index = "my_index";
    const type = "People";

    // Index a few document.
    const names = ["Ada Lovelace", "Alonzo Church", "Barbara Liskov"];

    const message = {
        refresh: "wait_for",
        body: names.flatMap((name) => [
            { index: { _index: index, _type: type } },
            { name },
        ]),
    };

    await client.bulk(message);

    // Search for documents.
    const response = await client.search({
        index,
        q: "name:Barbara Liskov",
    });

    const outputRows = response.hits.hits
        .map(
            ({ _id: id, _source: { name } }) =>
                `<tr><td>${id}</td><td>${name}</td></tr>\n`
        )
        .join("\n");

    // Clean up after ourselves.
    await Promise.allSettled(
        response.hits.hits.map(({ _id: id }) =>
            client.delete({
                index: index,
                type: type,
                id,
            })
        )
    );

    return `
    <table>
        <thead>
            <tr>
                <th>ID</th><th>Name</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};
const Memcached = require('memcached');
const config = require("platformsh-config").config();
const { promisify } = require('util');

exports.usageExample = async function() {
    const credentials = config.credentials('memcached');
    const client = new Memcached(`${credentials.host}:${credentials.port}`);

    // The MemcacheD client is not Promise-aware, so make it so.
    const memcachedGet = promisify(client.get).bind(client);
    const memcachedSet = promisify(client.set).bind(client);

    const key = 'Deploy-day';
    const value = 'Friday';

    // Set a value.
    await memcachedSet(key, value, 10);

    // Read it back.
    const test = await memcachedGet(key);

    return `Found value <strong>${test}</strong> for key <strong>${key}</strong>.`;
};
const mongodb = require("mongodb");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("mongodb");
    const MongoClient = mongodb.MongoClient;

    const client = await MongoClient.connect(
        config.formattedCredentials("mongodb", "mongodb")
    );

    const db = client.db(credentials["path"]);

    const collection = db.collection("startrek");

    const documents = [
        { name: "James Kirk", rank: "Admiral" },
        { name: "Jean-Luc Picard", rank: "Captain" },
        { name: "Benjamin Sisko", rank: "Prophet" },
        { name: "Katheryn Janeway", rank: "Captain" },
    ];

    await collection.insertMany(documents, { w: 1 });

    const result = await collection.find({ rank: "Captain" }).toArray();

    const outputRows = Object.values(result)
        .map(({ name, rank }) => `<tr><td>${name}</td><td>${rank}</td></tr>\n`)
        .join("\n");

    // Clean up after ourselves.
    collection.deleteMany();

    return `
    <table>
        <thead>
            <tr>
                <th>Name</th><th>Rank</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};
const mysql = require("mysql2/promise");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("database");

    const connection = await mysql.createConnection({
        host: credentials.host,
        port: credentials.port,
        user: credentials.username,
        password: credentials.password,
        database: credentials.path,
    });

    // Creating a table.
    await connection.query(
        `CREATE TABLE IF NOT EXISTS People (
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(30) NOT NULL,
            city VARCHAR(30) NOT NULL
        )`
    );

    // Insert data.
    await connection.query(
        `INSERT INTO People (name, city)
        VALUES
            ('Neil Armstrong', 'Moon'),
            ('Buzz Aldrin', 'Glen Ridge'),
            ('Sally Ride', 'La Jolla');`
    );

    // Show table.
    const [rows] = await connection.query("SELECT * FROM People");

    // Drop table.
    await connection.query("DROP TABLE People");

    const outputRows = rows
        .map(({ name, city }) => `<tr><td>${name}</td><td>${city}</td></tr>\n`)
        .join("\n");

    return `
    <table>
        <thead>
            <tr>
                <th>Name</th><th>City</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};
const pg = require("pg");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("postgresql");

    const client = new pg.Client({
        host: credentials.host,
        port: credentials.port,
        user: credentials.username,
        password: credentials.password,
        database: credentials.path,
    });

    client.connect();

    // Creating a table.
    await client.query(
        `CREATE TABLE IF NOT EXISTS People (
            id SERIAL PRIMARY KEY,
            name VARCHAR(30) NOT NULL,
            city VARCHAR(30) NOT NULL
        )`
    );

    // Insert data.
    await client.query(
        `INSERT INTO People (name, city)
        VALUES
            ('Neil Armstrong', 'Moon'),
            ('Buzz Aldrin', 'Glen Ridge'),
            ('Sally Ride', 'La Jolla');`
    );

    // Show table.
    const result = await client.query("SELECT * FROM People");

    // Drop table.
    await client.query("DROP TABLE People");

    const outputRows = result.rows
        .map(({ name, city }) => `<tr><td>${name}</td><td>${city}</td></tr>\n`)
        .join("\n");

    return `
    <table>
        <thead>
            <tr>
                <th>Name</th><th>City</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};
const redis = require('redis');
const config = require("platformsh-config").config();
const { promisify } = require('util');

exports.usageExample = async function() {
    const credentials = config.credentials('redis');
    const client = redis.createClient(credentials.port, credentials.host);

    // The Redis client is not Promise-aware, so make it so.
    const redisGet = promisify(client.get).bind(client);
    const redisSet = promisify(client.set).bind(client);

    const key = 'Deploy day';
    const value = 'Friday';

    // Set a value.
    await redisSet(key, value);

    // Read it back.
    const test = await redisGet(key);

    return `Found value <strong>${test}</strong> for key <strong>${key}</strong>.`;
};
const solr = require("solr-node");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const client = new solr(config.formattedCredentials("solr", "solr-node"));

    // Add a document.
    const addResult = await client.update({
        id: 123,
        name: "Valentina Tereshkova",
    });

    // Flush writes so that we can query against them.
    await client.softCommit();

    // Select one document:
    const strQuery = client.query().q();
    const writeResult = await client.search(strQuery);

    // Delete one document.
    const deleteResult = await client.delete({ id: 123 });

    return `
    Adding one document. Status (0 is success): ${addResult.responseHeader.status}<br />
    Selecting documents (1 expected): ${writeResult.response.numFound}<br />
    Deleting one document. Status (0 is success): ${deleteResult.responseHeader.status}<br />
    `;
};

platformsh-config package

Project templates

Gatsby with Strapi

image

This template builds a two application project to deploy the Headless CMS pattern using Gatsby as its frontend and Strapi for its backend. The `gatsby-source-strapi` source plugin is used to pull data from Strapi during the `post_deploy` hook into the Gatsby Data Layer and build the frontend site. Gatsby utilizes the Web PaaS Configuration Reader library for Node.js to define the backend data source in its configuration. It is intended for you to use as a starting point and modify for your own needs.

Note that there are several setup steps required after the first deploy to create your first content types and access permissions in Strapi. See the included README's post-install section for details.

Gatsby is a free and open source framework based on React that helps developers build blazing fast websites and apps, and Strapi is a Headless CMS framework written in Node.js.

Features

  • Node.js 14
  • PostgreSQL 12
  • Automatic TLS certificates
  • yarn-based build
  • Multi-app configuration
  • Delayed SSG build (post deploy hook)

View the repository on GitHub.

Probot

image

This template builds a simple GitHub App using [Probot](https://github.com/probot/probot) for Node.js. It includes a minimalist skeleton GitHub app that demonstrates a basic GitHub connection response. It is intended for you to use as a starting point and modify for your own needs.

Note that there are several setup steps required after first deploy to connect your project to GitHub. See the included README file for details.

Probot is a framework for building GitHub Apps in Node.js.

Features

  • Node.js 12
  • Automatic TLS certificates
  • npm-based build

View the repository on GitHub.

strapi

image

This template builds a Strapi backend for Web PaaS, which can be used to quickly create an API that can be served by itself or as a Headless CMS data source for another frontend application in the same project. This repository does not include a frontend application, but you can add one of your choice and access Strapi by defining it in a relationship in your frontend's .platform.app.yaml file.

Strapi is a Headless CMS framework written in Node.js.

Features

  • Node.js 12
  • PostgreSQL 12
  • Automatic TLS certificates
  • npm-based build
  • OpenAPI spec generation
  • Automatic public API documentation

View the repository on GitHub.

Gatsby with WordPress

image

This template builds a two application project to deploy the Headless CMS pattern using Gatsby as its frontend and WordPress for its backend. The `gatsby-source-WordPress` source plugin is used to pull data from WordPress during the `post_deploy` hook into the Gatsby Data Layer and build the frontend site. Gatsby utilizes the Web PaaS Configuration Reader library for Node.js to define the backend data source in its configuration. It is intended for you to use as a starting point and modify for your own needs.

Note that after you have completed the WordPress installation, the project will require a redeploy to build and deploy Gatsby for the first time. See the included README's post-install section for details.

Gatsby is a free and open source framework based on React that helps developers build statically-generated websites and apps, and WordPress is a blogging and lightweight CMS written in PHP.

Features

  • Node.js 14
  • PHP 7.4
  • MariaDB 10.4
  • Automatic TLS certificates
  • npm-based build for Gatsby
  • Composer-based build for WordPress
  • Multi-app configuration
  • Delayed SSG build (post deploy hook)

View the repository on GitHub.

Gatsby

image

This template builds a simple application using Gatsby. Gatsby is a free and open source framework based on React that helps developers build blazing fast websites and apps. The website is statically generated by a Node.js application during the build step, and then served statically at runtime.

Gatsby is a free and open source framework based on React that helps developers build blazing fast websites and apps.

Features

  • Node.js 14
  • Automatic TLS certificates
  • yarn-based build

View the repository on GitHub.

Koa

image

This template demonstrates building the Koa framework for Web PaaS. It includes a minimalist application skeleton that demonstrates how to connect to a MariaDB server for data storage. It is intended for you to use as a starting point and modify for your own needs.

Koa is a lightweight web microframework for Node.js.

Features

  • Node.js 10
  • MariaDB 10.2
  • Automatic TLS certificates
  • npm-based build

View the repository on GitHub.

Node.js

image

This template builds a simple application using the Node.js built-in `http` web server. It includes a minimalist application skeleton that demonstrates how to connect to the included MariaDB server, but you are free to alter it as needed.

Node.js is an open-source JavaScript runtime built on Chrome's V8 JavaScript engine.

Features

  • Node.js 14
  • MariaDB 10.4
  • Automatic TLS certificates
  • npm-based build

View the repository on GitHub.

Next.js

image

This template builds a simple application using the Next.js web framework. It includes a minimal application skeleton that demonstrates how to set up an optimized build using Next.js and Yarn, as well as how to begin defining individual pages (such as the /api/hello) endpoint that comes pre-defined with this template.

Next.js is an open-source web framework written for Javascript.

Features

  • Node.js 14
  • Automatic TLS certificates
  • yarn-based build

View the repository on GitHub.

Express

image

This template demonstrates building the Express framework for Web PaaS. It includes a minimalist application skeleton that demonstrates how to connect to a MariaDB server. It is intended for you to use as a starting point and modify for your own needs.

Express is a minimalist web framework written in Node.js.

Features

  • Node.js 14
  • MariaDB 10.4
  • Automatic TLS certificates
  • npm-based build

View the repository on GitHub.

NuxtJS

image

This template builds a simple application using the NuxtJS web framework that can be used as a starting point.

NuxtJS is an open-source web framework based on Vue.js.

Features

  • Node.js 14
  • Automatic TLS certificates
  • yarn-based build

View the repository on GitHub.

Gatsby with Drupal

image

This template builds a two-application project to deploy the Headless CMS pattern using Gatsby as its frontend and Drupal 8 for its backend. The gatsby-source-drupal source plugin is used to pull data from Drupal during the post_deploy hook into the Gatsby Data Layer and build the frontend site. Gatsby utilizes the Web PaaS Configuration Reader library for Node.js to define the backend data source in its configuration. It is intended for you to use as a starting point and modify for your own needs.

Note that after you have completed the Drupal installation and included a few articles, the project will require a redeploy to build and deploy Gatsby for the first time. See the included README's post-install section for details.

Gatsby is a free and open source framework based on React that helps developers build statically-generated websites and apps, and Drupal is a flexible and extensible PHP-based CMS framework.

Features

  • Node.js 12
  • PHP 7.4
  • MariaDB 10.4
  • Redis 5.0
  • Automatic TLS certificates
  • npm-based build for Gatsby
  • Composer-based build for Drupal
  • Multi-app configuration
  • Delayed SSG build (post deploy hook)

View the repository on GitHub.

Directus

This template demonstrates building Directus for Web PaaS. It includes a quickstart application configured to run with PostgreSQL. It is intended for you to use as a starting point and modify for your own needs.

Directus is an open-source platform that allows you to create and manage an API from data stored in a database.

Features

  • Node.js 14
  • PostgreSQL 12
  • Redis 6.0
  • Automatic TLS certificates
  • npm-based build

View the repository on GitHub.


Did you find this guide useful?

Please feel free to give any suggestions in order to improve this documentation.

Whether your feedback is about images, content, or structure, please share it, so that we can improve it together.

Your support requests will not be processed via this form. To do this, please use the "Create a ticket" form.

Thank you. Your feedback has been received.


These guides might also interest you...

OVHcloud Community

Access your community space. Ask questions, search for information, post content, and interact with other OVHcloud Community members.

Discuss with the OVHcloud community

In accordance with the 2006/112/CE Directive, modified on 01/01/2015, prices exclude VAT. VAT may vary according to the customer's country of residence.