JavaScript/Node.js
Back to home
On this page
Note
You can now use composable image (BETA) to install runtimes and tools in your application container. To find out more, see the dedicated documentation page.
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
You can select the major version. But the latest compatible minor version is applied automatically and canโt be overridden.
Patch versions are applied periodically for bug fixes and the like. When you deploy your app, you always get the latest available patches.
Grid and Dedicated Gen 3 | Dedicated Gen 2 |
---|---|
|
None available |
Specify the language
To use Node.js, specify nodejs
as your app’s type
:
type: 'nodejs:<VERSION_NUMBER>'
For example:
type: 'nodejs:22'
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 in the future, so migrate to one of the supported versions.
Grid | Dedicated Gen 2 |
---|---|
|
|
Usage example
To use JavaScript with Node.js on Platform.sh, configure your app configuration (a complete example is included at the end).
1. Specify the version
Choose a version from the list of supported versions and add it to your app configuration:
type: 'nodejs:22'
2. Specify any global dependencies
Add the following to your app configuration:
type: 'nodejs:22'
dependencies:
nodejs:
sharp: "*"
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:
type: 'nodejs:22'
dependencies:
nodejs:
sharp: "*"
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):
type: 'nodejs:22'
dependencies:
nodejs:
sharp: "*"
hooks:
build: |
npm run setup-assets
npm run build
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:
name: node-app
type: 'nodejs:22'
disk: 512
dependencies:
nodejs:
sharp: "*"
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:
- Turn off the default use of npm:
build:
flavor: none
-
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.
- Use Corepack to run Yarn in your build hook:
type: 'nodejs:22'
hooks:
build: |
corepack yarn install
- Enable Corepack (which is opt-in):
type: 'nodejs:22'
dependencies:
nodejs:
corepack: "*"
- Use Corepack to run Yarn in your build hook:
type: 'nodejs:22'
hooks:
build: |
corepack yarn install
- Add Yarn as a global dependency:
type: 'nodejs:22'
dependencies:
nodejs:
yarn: "1.22.19"
- Install dependencies in the
build
hook:
type: 'nodejs:22'
hooks:
build: |
yarn --frozen-lockfile
Use Bun as a package manager
Availability
Bun is available as a runtime and package manager for Node.js versions 20 or above.
To switch to Bun to manage dependencies, use the following configuration:
# The name of your app.
name: myapp
# Choose Node.js version 20 or above.
type: 'nodejs:20'
# Override the default Node.js build flavor.
build:
flavor: none
# Use Bun to install the dependencies.
hooks:
build: bun install
Use Bun as a runtime
You can even use Bun as a runtime by adjusting the start
command as follows:
# The name of your app.
name: myapp
# Choose Node.js version 20 or above.
type: 'nodejs:20'
# Override the default Node.js build flavor.
build:
flavor: none
# Use Bun to install the dependencies.
hooks:
build: bun install
# In the start command replace node with Bun.
web:
commands:
start: 'bun app.js'
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 theNode.js configuration reader library. 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 should help you get a project ready for production.
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.
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.
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.
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.
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.
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 18
- Automatic TLS certificates
- yarn-based build
View the repository on GitHub.
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.