Node.js

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

Supported versions 

Grid and Dedicated Gen 3 Dedicated Gen 2
  • 18
  • 16
  • 14
  • 14
  • 12
  • 10

Specify the language 

To use Node.js, specify nodejs as your app’s type:

.platform.app.yaml
type: 'nodejs:<VERSION_NUMBER>'

For example:

.platform.app.yaml
type: 'nodejs:18'

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

Deprecated versions 

The following versions are deprecated. They’re available, but they aren’t receiving security updates from upstream and aren’t guaranteed to work. They’ll be removed at some point in the future, so you should migrate to one of the supported versions.

Grid Dedicated Gen 2
  • 12
  • 10
  • 8
  • 6
  • 4.8
  • 4.7
  • 0.12
  • 9.8

Usage example 

To use Node.js on Platform.sh 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:

.platform.app.yaml
type: 'nodejs:18'

2. Specify any global dependencies 

Add the following to your app configuration:

.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:

.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):

.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 Platform.sh 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 Platform.sh configuration
server.listen(config.port);

Complete example 

A complete basic app configuration looks like the following:

.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, Platform.sh assumes you’re using npm as a package manager. If your code has a package.json, the following command is run as part of the default build flavor:

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:

  1. Turn off the default use of npm:

    .platform.app.yaml
    build:
        flavor: none
  2. Specify the version of Yarn you want:

    package.json
    {
      ...
      "packageManager": "yarn@3.2.1"
    }

What you do next depends on the versions of Yarn and Node.js you want.

  1. Use Corepack to run Yarn in your build hook:

    .platform.app.yaml
    hooks:
        build: |
                    corepack yarn install
  1. Enable Corepack (which is opt-in):

    .platform.app.yaml
    dependencies:
        nodejs:
            corepack: "*"
  2. Use Corepack to run Yarn in your build hook:

    .platform.app.yaml
    hooks:
        build: |
                    corepack yarn install
  1. Add Yarn as a global dependency:

    .platform.app.yaml
    dependencies:
        nodejs:
            yarn: "1.22.19"
  2. Install dependencies in the build hook:

    .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 />
    `;
};

Configuration reader 

While you can read the environment directly from your app, you might want to use the platformsh-config package . It decodes service credentials, the correct port, and other information for you.

Project templates 

The following list shows templates available for Node.js apps. A template is a starting point for building your project. It isn’t yet ready for a production environment, but it should help you get there.

Directus

Directus

This template demonstrates building Directus for Platform.sh. 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.

Deploy on Platform.sh

Eleventy with Strapi

Eleventy with Strapi

This template deploys a two application project on Platform.sh: one for a frontend static site generator, Eleventy, and the other for a backend headless CMS, Strapi. Like our other "decoupled" templates, Eleventy's build is delayed until the post_deploy hook, at which point the backend Strapi content data becomes available to query using GraphQL. That data then is reformatted into "Blogs" on the frontend. Both applications utilize the Platform.sh Configuration Reader library for Node.js. 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. An article content type has already been committed, but you will still need to follow the post deploy instructions to add content and define permissions for Eleventy to consume it.

Eleventy is a static site generator written in Node.js, and Strapi is a headless CMS framework also written in Node.js.

Features:

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

View the repository on GitHub.

Deploy on Platform.sh

Express

Express

This template demonstrates building the Express framework for Platform.sh. 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.

Deploy on Platform.sh

Gatsby

Gatsby

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 16
  • Automatic TLS certificates
  • yarn-based build

View the repository on GitHub.

Deploy on Platform.sh

Gatsby with Drupal

Gatsby with Drupal

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 Platform.sh 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.

Deploy on Platform.sh

Gatsby with Strapi

Gatsby with Strapi

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 Platform.sh 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.

Deploy on Platform.sh

Gatsby with WordPress

Gatsby with WordPress

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 Platform.sh 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.

Deploy on Platform.sh

Koa

Koa

This template demonstrates building the Koa framework for Platform.sh. 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.

Deploy on Platform.sh

Next.js

Next.js

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.

Deploy on Platform.sh

Next.js Drupal

Next.js Drupal

This template demonstrates a multi-app deployment on Platform.sh, in this case, a Next.js frontend consuming data from a Drupal 9 backend running on the same environment. It is based largely on the configuration instructions provided by the Next-Drupal project by Chapter Three.

Next.js is an open-source web framework written for Javascript, and Drupal is a flexible and extensible PHP-based CMS framework.

Features:

  • PHP 8.1
  • Node.js 16
  • MariaDB 10.4
  • Redis 6.0
  • Network Storage
  • Automatic TLS certificates
  • Multi-app configuration
  • yarn-based builds
  • Delayed SSG build (post deploy hook)

View the repository on GitHub.

Deploy on Platform.sh

Next.js WordPress

Next.js WordPress

This template demonstrates a multi-app deployment on Platform.sh, in this case, a Next.js frontend consuming data from a WordPress backend running on the same environment. It is based largely on the instructions provided by NextJS for a WordPress Demo site.

Next.js is an open-source web framework written for Javascript, and WordPress is a flexible and extensible PHP-based CMS framework.

Features:

  • PHP 7.4
  • Node.js 16
  • MariaDB 10.4
  • Network Storage
  • Automatic TLS certificates
  • Multi-app configuration
  • yarn-based builds
  • Delayed SSG build (post deploy hook)

View the repository on GitHub.

Deploy on Platform.sh

Node.js

Node.js

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.

Deploy on Platform.sh

NuxtJS

NuxtJS

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.

Deploy on Platform.sh

Probot

Probot

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.

Deploy on Platform.sh

strapi

strapi

This template builds a Strapi backend for Platform.sh, 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.

Deploy on Platform.sh

strapi4

strapi4

This template builds a Strapi version 4 backend for Platform.sh, 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
  • yarn-based build

View the repository on GitHub.

Deploy on Platform.sh