Lesson 21 · Node.js on IBM i — From RPG Developer to Modern IBM i Developer
Use Mapepire as an Alternative Db2 Connector
Run the completed Tools Rental application through Mapepire and learn when it is a better fit than a local IBM i connector.
Our application has used idb-pconnector because Node.js and Db2 run on the same IBM i. Mapepire gives us another choice: the Node.js application can run on IBM i or another system and still use Db2 for i.
This is an optional path. We will not rebuild the application or change its API. We will replace only the database module and keep the same seven functions used by the rest of the project.
Choose the connector that fits the deployment
Neither connector is the right answer for every application.
idb-pconnector |
Mapepire | |
|---|---|---|
| Where Node.js runs | On IBM i | On IBM i or another supported system |
| How it reaches Db2 | Local native connector | Mapepire transport, commonly a secure WebSocket |
| Credentials | Uses the local IBM i job context | Uses an IBM i profile for a daemon connection |
| Extra service | No | The WebSocket option requires the Mapepire server |
| A good fit | An application deployed directly on IBM i | Development workstations, containers, cloud services, or a shared connection approach |
If the Tools Rental API will always run on IBM i, the original connector remains the simpler choice. Mapepire becomes useful when the Node.js runtime needs to live somewhere else or the team wants the same JavaScript database client in more than one environment.
Prepare the Mapepire server
For the WebSocket approach used in this lesson, an IBM i administrator installs and starts the Mapepire server. The recommended RPM installation is:
yum install mapepire-server service-commander
sc start mapepire
The default port is 8076. Treat it as a database entry point, not as a public web service. Limit which systems can reach it, use TLS with a certificate the client can validate, and follow your organization’s rules for IBM i profiles and password management.
The Mapepire documentation also describes SSH and local single-process transports. Begin with one transport that your IBM i administrator can support rather than mixing several connection methods into the first application.
Install the client
In the Tools Rental project, remove the old connector only after deciding to use Mapepire for this deployment:
npm uninstall idb-pconnector
npm install @ibm/mapepire-js
Do not remove idb-pconnector from an existing release until its Mapepire replacement has passed the same integration tests.
Add these names to .env.example:
DB2_HOST=ibmi.example.com
DB2_PORT=8076
DB2_USER=TOOLAPP
DB2_PASS=
DB2_CA_FILE=
Keep the real password only in the ignored .env file or in your approved secrets system. The application profile should have only the Db2 authority the Tools Rental operations require.
This is a real difference from the local connector. In Lesson 18 the TOOLAPP profile was created with PASSWORD(*NONE) because the application ran as that profile on IBM i. A Mapepire connection signs on over the network, so the profile it uses needs a password, and that password must be stored, protected, and changed on a schedule.
Trust the server certificate
Mapepire always connects over TLS. When no certificate has been configured, the Mapepire server generates a self-signed one. A client that validates certificates, as ours does with rejectUnauthorized: true, refuses a self-signed certificate until it is told which one to trust.
For a publicly trusted server certificate, leave DB2_CA_FILE empty so Node.js uses its standard trust store. For an organizational CA or a self-signed certificate, obtain the PEM certificate through a trusted administrator and set DB2_CA_FILE to that local file. The module below loads that fixed trust material before connecting; it does not automatically trust a certificate fetched from the unverified endpoint.
Do not set rejectUnauthorized: false to make an error disappear. That switches certificate checking off entirely.
Replace the database module
Replace src/db.js with this Mapepire implementation:
const { readFileSync } = require('node:fs');
const { Pool } = require('@ibm/mapepire-js');
let poolPromise;
function readCredentials() {
const port = Number(process.env.DB2_PORT ?? 8076);
if (!process.env.DB2_HOST || !process.env.DB2_USER || !process.env.DB2_PASS) {
throw new Error('DB2_HOST, DB2_USER, and DB2_PASS are required');
}
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('DB2_PORT must be a valid TCP port');
}
return {
host: process.env.DB2_HOST,
port,
user: process.env.DB2_USER,
password: process.env.DB2_PASS,
rejectUnauthorized: true
};
}
async function createPool() {
const creds = readCredentials();
if (process.env.DB2_CA_FILE) {
creds.ca = readFileSync(process.env.DB2_CA_FILE, 'utf8');
}
const pool = new Pool({
creds,
startingSize: 1,
maxSize: 5
});
await pool.init();
return pool;
}
function getPool() {
if (!poolPromise) {
poolPromise = createPool().catch((error) => {
poolPromise = undefined;
throw error;
});
}
return poolPromise;
}
async function runRows(sql, parameters = []) {
const pool = await getPool();
const options = parameters.length > 0 ? { parameters } : undefined;
const result = await pool.execute(sql, options);
return result.data ?? [];
}
async function listAvailableTools() {
return runRows(`
SELECT TOOL_ID, NAME, CATEGORY, DAILY_RATE, STATUS
FROM TOOLRENT.TOOLS
WHERE STATUS = 'AVAILABLE'
ORDER BY NAME
`);
}
async function findToolById(toolId) {
const rows = await runRows(`
SELECT TOOL_ID, NAME, CATEGORY, DAILY_RATE, STATUS
FROM TOOLRENT.TOOLS
WHERE TOOL_ID = ?
`, [toolId]);
return rows[0] ?? null;
}
async function listActiveCustomers() {
return runRows(`
SELECT CUSTOMER_ID, NAME, EMAIL
FROM TOOLRENT.CUSTOMERS
WHERE ACTIVE = 1
ORDER BY NAME
`);
}
async function rentTool({ toolId, customerId, dueDate }) {
await runRows(
'CALL TOOLRENT.RENT_TOOL(?, ?, ?)',
[toolId, customerId, dueDate]
);
}
async function returnTool(rentalId) {
await runRows('CALL TOOLRENT.RETURN_TOOL(?)', [rentalId]);
}
async function listOpenRentals() {
return runRows(`
SELECT R.RENTAL_ID,
T.TOOL_ID,
T.NAME AS TOOL_NAME,
C.CUSTOMER_ID,
C.NAME AS CUSTOMER_NAME,
R.RENTED_AT,
R.DUE_DATE,
CASE WHEN R.DUE_DATE < CURRENT_DATE
THEN 1 ELSE 0 END AS OVERDUE
FROM TOOLRENT.RENTALS R
JOIN TOOLRENT.TOOLS T ON T.TOOL_ID = R.TOOL_ID
JOIN TOOLRENT.CUSTOMERS C ON C.CUSTOMER_ID = R.CUSTOMER_ID
WHERE R.RETURNED_AT IS NULL
ORDER BY R.DUE_DATE, R.RENTAL_ID
`);
}
async function checkDatabase() {
await runRows('VALUES 1');
}
async function closeDatabase() {
if (!poolPromise) return;
const pool = await poolPromise;
pool.end();
poolPromise = undefined;
}
module.exports = {
checkDatabase,
closeDatabase,
findToolById,
listActiveCustomers,
listAvailableTools,
listOpenRentals,
rentTool,
returnTool
};
The seven functions the server calls have not changed: checkDatabase, findToolById, listActiveCustomers, listAvailableTools, listOpenRentals, rentTool, and returnTool. Fastify still calls them without knowing which connector is behind them. Only the connection setup and the small runRows helper are different, plus one new function, closeDatabase, which the next section uses.
Three details are worth reading closely:
getPoolcreates the pool the first time a query needs it and reuses it afterward. If the first attempt fails, it forgets the failure so that a later request can try again.createPooluses the standard trust store or the administrator-supplied certificate file, as described above.- A failed statement throws an error whose message includes the SQLSTATE. The error handler from Lesson 15 searches the message for our
75001to75004codes, so the same 409 and 400 responses still apply. Confirm that with one deliberately repeated rental.
The parameter markers are still important. Values such as toolId and dueDate remain separate from the SQL text instead of being joined into a string.
Close the pool with the server
Inside buildServer, add an onClose hook after the server is created:
server.addHook('onClose', async () => {
if (db.closeDatabase) {
await db.closeDatabase();
}
});
The check keeps the route tests simple because their small fake database does not need a connection pool.
Run the same application checks
The start script from Lesson 18 already loads .env, so start the server as usual:
npm start
Then repeat the checks already used in the course:
curl http://127.0.0.1:3000/health
curl -i http://127.0.0.1:3000/health/ready
curl http://127.0.0.1:3000/tools
curl http://127.0.0.1:3000/customers
curl http://127.0.0.1:3000/rentals/open
npm test
The readiness check is the important one here. It returns 200 only when the certificate was accepted, the password was correct, and a query reached Db2. Finish by opening the browser page and renting and returning one tool.
Use a dedicated test schema for rent and return integration tests. The route tests use a fake database, so they can confirm API behavior without proving that Mapepire, TLS, IBM i authority, and the SQL procedures work together.
Keep the operational difference visible
Mapepire removes the requirement to install an IBM i-native Node.js package, but it does not remove operations work. The team now owns a network path, server configuration, TLS certificates, application credentials, and connection-pool monitoring.
Record the chosen connector in the deployment instructions. Test a stopped Mapepire server, an expired certificate, an invalid password, and a profile without table authority. A useful failure should reach the protected application log while the API continues to return its controlled public error.
The important design choice is not which package has the newer name. It is whether the connection method matches where the application runs and whether the team can secure, test, and support it.
References
Documentation and references used for this lesson.

Comments
Share your thoughts, questions, or real-world IBM i experiences related to this article.