Lesson 17 · Node.js on IBM i — From RPG Developer to Modern IBM i Developer
Add a Simple Browser Interface
Serve a small rental-counter screen from the Node.js application and connect it to the tools, customers, rentals, and returns APIs.
The API works, but a rental-counter employee should not need curl. We will add one small browser screen that uses the same routes we have already tested.
Add the customer query
Add this function to src/db.js and export it:
async function listActiveCustomers() {
const rows = await pool.runSql(`
SELECT CUSTOMER_ID, NAME, EMAIL
FROM TOOLRENT.CUSTOMERS
WHERE ACTIVE = 1
ORDER BY NAME
`);
return rows ?? [];
}
Add the route to src/server.js:
server.get('/customers', async () => db.listActiveCustomers());
Also add listActiveCustomers to the fake database in test/server.test.js, so the tests describe the same six functions as the real module:
async listActiveCustomers() {
return [{ CUSTOMER_ID: 1, NAME: 'Avery Singh' }];
},
Serve static files
Install the Fastify static-file plugin:
npm install @fastify/static
mkdir public
At the top of src/server.js:
const path = require('node:path');
const fastifyStatic = require('@fastify/static');
Inside buildServer, before the routes:
server.register(fastifyStatic, {
root: path.join(__dirname, '..', 'public')
});
Create the page
Create public/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tools Rental</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<main>
<h1>Tools Rental</h1>
<p id="message" role="status"></p>
<section>
<h2>Available tools</h2>
<label>
Customer
<select id="customer"></select>
</label>
<label>
Due date
<input id="due-date" type="date">
</label>
<div id="tools"></div>
</section>
<section>
<h2>Open rentals</h2>
<div id="rentals"></div>
</section>
</main>
<script src="/app.js" defer></script>
</body>
</html>
Create public/app.js:
const toolsElement = document.querySelector('#tools');
const rentalsElement = document.querySelector('#rentals');
const customerElement = document.querySelector('#customer');
const dueDateElement = document.querySelector('#due-date');
const messageElement = document.querySelector('#message');
const defaultDueDate = new Date();
defaultDueDate.setDate(defaultDueDate.getDate() + 7);
dueDateElement.min = new Date().toISOString().slice(0, 10);
dueDateElement.value = defaultDueDate.toISOString().slice(0, 10);
async function request(url, options) {
const response = await fetch(url, options);
const body = await response.json();
if (!response.ok) {
throw new Error(body.message ?? 'Request failed');
}
return body;
}
function createCard(title, detail, buttonText, dataName, id) {
const card = document.createElement('article');
const heading = document.createElement('h3');
const text = document.createElement('p');
const button = document.createElement('button');
heading.textContent = title;
text.textContent = detail;
button.textContent = buttonText;
button.dataset[dataName] = id;
card.append(heading, text, button);
return card;
}
async function loadCustomers() {
const customers = await request('/customers');
const options = customers.map((customer) => {
const option = document.createElement('option');
option.value = customer.CUSTOMER_ID;
option.textContent = customer.NAME;
return option;
});
customerElement.replaceChildren(...options);
}
async function loadTools() {
const tools = await request('/tools');
const cards = tools.map((tool) => createCard(
tool.NAME,
`${tool.CATEGORY} · $${Number(tool.DAILY_RATE).toFixed(2)} per day`,
'Rent this tool',
'rent',
tool.TOOL_ID
));
toolsElement.replaceChildren(...cards);
if (cards.length === 0) {
toolsElement.textContent = 'No tools are available.';
}
}
async function loadRentals() {
const rentals = await request('/rentals/open');
const cards = rentals.map((rental) => createCard(
rental.TOOL_NAME,
`${rental.CUSTOMER_NAME} · due ${rental.DUE_DATE}`,
'Record return',
'return',
rental.RENTAL_ID
));
rentalsElement.replaceChildren(...cards);
if (cards.length === 0) {
rentalsElement.textContent = 'There are no open rentals.';
}
}
document.addEventListener('click', async (event) => {
const toolId = event.target.dataset.rent;
const rentalId = event.target.dataset.return;
if (!toolId && !rentalId) {
return;
}
try {
if (toolId) {
await request('/rentals', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
toolId: Number(toolId),
customerId: Number(customerElement.value),
dueDate: dueDateElement.value
})
});
messageElement.textContent = 'Tool rented.';
}
if (rentalId) {
await request(`/rentals/${rentalId}/return`, { method: 'POST' });
messageElement.textContent = 'Return recorded.';
}
await Promise.all([loadTools(), loadRentals()]);
} catch (error) {
messageElement.textContent = error.message;
}
});
Promise.all([loadCustomers(), loadTools(), loadRentals()])
.catch((error) => {
messageElement.textContent = error.message;
});
Create public/styles.css:
body {
margin: 0;
font-family: system-ui, sans-serif;
line-height: 1.5;
color: #1c1c1c;
background: #f6f5f2;
}
main {
max-width: 48rem;
margin: 0 auto;
padding: 1.5rem 1rem 3rem;
}
label {
display: block;
margin-bottom: 1rem;
font-weight: 600;
}
select,
input {
display: block;
margin-top: 0.25rem;
padding: 0.5rem;
font: inherit;
}
article {
margin-bottom: 0.75rem;
padding: 1rem;
background: #ffffff;
border: 1px solid #d8d4cc;
border-radius: 0.5rem;
}
article h3,
article p {
margin: 0 0 0.5rem;
}
button {
padding: 0.6rem 1rem;
font: inherit;
color: #ffffff;
background: #1f5f8b;
border: 0;
border-radius: 0.375rem;
cursor: pointer;
}
button:focus-visible,
select:focus-visible,
input:focus-visible {
outline: 3px solid #f0a500;
outline-offset: 2px;
}
#message {
min-height: 1.5rem;
font-weight: 600;
}
It is deliberately plain: readable text, a visible focus outline for keyboard users, and buttons large enough to use comfortably. Styling should support the task, not hide missing behavior.
Read the browser code
public/app.js runs in the browser, not on IBM i. It has four parts:
requestcalls one of our API routes withfetchand turns a failed response into an error carrying the API’s message.loadCustomers,loadTools, andloadRentalseach call one route and build the matching part of the page.- The
clicklistener reacts to the two kinds of button.data-rentanddata-returnattributes tell it which tool or rental the button belongs to. A click on anything else is ignored. - The last statement loads all three lists when the page opens.
The page builds elements with textContent rather than placing database values into HTML strings. Never assume a name stored in a database is safe HTML.
The page calculates dates on the user’s workstation, while the due-date rule is checked on IBM i. Near midnight, or across time zones, the two can disagree by a day. The server’s answer is the one that counts, and the page shows its message when a date is refused.
Try it in a browser
The server still listens on 127.0.0.1 by default. For a safe development check, keep that setting and create an SSH tunnel from your workstation:
ssh -L 3000:127.0.0.1:3000 myuser@your-system
Then open http://127.0.0.1:3000/ in your workstation browser. If your team instead binds the service to an IBM i network interface, use an authorized development network and review the host, firewall, TLS, and access settings first.
You should now be able to rent and return a tool without using SQL or curl.
Check your files
The server and the database module have grown a few lines at a time over seven lessons. Compare yours with the complete versions below before continuing.
src/db.js:
const { DBPool } = require('idb-pconnector');
const pool = new DBPool();
async function listAvailableTools() {
const sql = `
SELECT TOOL_ID, NAME, CATEGORY, DAILY_RATE, STATUS
FROM TOOLRENT.TOOLS
WHERE STATUS = 'AVAILABLE'
ORDER BY NAME
`;
return (await pool.runSql(sql)) ?? [];
}
async function findToolById(toolId) {
const sql = `
SELECT TOOL_ID, NAME, CATEGORY, DAILY_RATE, STATUS
FROM TOOLRENT.TOOLS
WHERE TOOL_ID = ?
`;
const result = await pool.prepareExecute(sql, [toolId]);
return result?.resultSet?.[0] ?? null;
}
async function listActiveCustomers() {
const rows = await pool.runSql(`
SELECT CUSTOMER_ID, NAME, EMAIL
FROM TOOLRENT.CUSTOMERS
WHERE ACTIVE = 1
ORDER BY NAME
`);
return rows ?? [];
}
async function rentTool({ toolId, customerId, dueDate }) {
const sql = 'CALL TOOLRENT.RENT_TOOL(?, ?, ?)';
await pool.prepareExecute(sql, [
{ value: toolId, io: 'in' },
{ value: customerId, io: 'in' },
{ value: dueDate, io: 'in' }
]);
}
async function returnTool(rentalId) {
await pool.prepareExecute(
'CALL TOOLRENT.RETURN_TOOL(?)',
[{ value: rentalId, io: 'in' }]
);
}
async function listOpenRentals() {
const rows = await pool.runSql(`
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
`);
return rows ?? [];
}
module.exports = {
findToolById,
listActiveCustomers,
listAvailableTools,
listOpenRentals,
rentTool,
returnTool
};
src/server.js:
const path = require('node:path');
const Fastify = require('fastify');
const fastifyStatic = require('@fastify/static');
function buildServer({ db = require('./db'), logger = true } = {}) {
const server = Fastify({ logger });
server.register(fastifyStatic, {
root: path.join(__dirname, '..', 'public')
});
server.get('/health', async () => {
return { status: 'ok' };
});
server.get('/tools', async () => db.listAvailableTools());
server.get('/tools/:toolId', {
schema: {
params: {
type: 'object',
required: ['toolId'],
properties: {
toolId: { type: 'integer', minimum: 1 }
}
}
}
}, async (request, reply) => {
const tool = await db.findToolById(request.params.toolId);
if (!tool) {
return reply.code(404).send({ message: 'Tool not found' });
}
return tool;
});
server.get('/customers', async () => db.listActiveCustomers());
server.get('/rentals/open', async () => db.listOpenRentals());
server.post('/rentals', {
schema: {
body: {
type: 'object',
additionalProperties: false,
required: ['toolId', 'customerId', 'dueDate'],
properties: {
toolId: { type: 'integer', minimum: 1 },
customerId: { type: 'integer', minimum: 1 },
dueDate: { type: 'string', format: 'date' }
}
}
}
}, async (request, reply) => {
await db.rentTool(request.body);
return reply.code(201).send({ message: 'Tool rented' });
});
server.post('/rentals/:rentalId/return', {
schema: {
params: {
type: 'object',
required: ['rentalId'],
properties: {
rentalId: { type: 'integer', minimum: 1 }
}
}
}
}, async (request) => {
await db.returnTool(request.params.rentalId);
return { message: 'Tool returned' };
});
server.setErrorHandler((error, request, reply) => {
if (error.validation) {
return reply.code(400).send({
code: 'INVALID_REQUEST',
message: 'Check the request values and try again.'
});
}
const detail = `${error.message ?? ''} ${error.stack ?? ''}`;
if (detail.includes('75001')) {
return reply.code(409).send({
code: 'TOOL_NOT_AVAILABLE',
message: 'This tool is no longer available.'
});
}
if (detail.includes('75002')) {
return reply.code(409).send({
code: 'CUSTOMER_NOT_ACTIVE',
message: 'This customer cannot begin a new rental.'
});
}
if (detail.includes('75003')) {
return reply.code(409).send({
code: 'RENTAL_ALREADY_CLOSED',
message: 'This rental is not open.'
});
}
if (detail.includes('75004')) {
return reply.code(400).send({
code: 'INVALID_DUE_DATE',
message: 'The due date cannot be in the past.'
});
}
if (error.statusCode >= 400 && error.statusCode < 500) {
return reply.code(error.statusCode).send({
code: 'BAD_REQUEST',
message: 'The request could not be understood.'
});
}
request.log.error({ err: error }, 'Request failed');
return reply.code(500).send({
code: 'INTERNAL_ERROR',
message: 'The request could not be completed.'
});
});
return server;
}
async function start() {
const server = buildServer();
const port = Number(process.env.PORT ?? 3000);
const host = process.env.HOST ?? '127.0.0.1';
try {
await server.listen({ port, host });
} catch (error) {
server.log.error(error);
process.exitCode = 1;
}
}
if (require.main === module) {
start();
}
module.exports = { buildServer };
Run the tests, then commit the checkpoint:
npm test
git add package.json package-lock.json public src test
git commit -m "Add browser interface"
The application is now visible and usable. Before deployment, we need to separate configuration, restrict authority, and decide how users will be authenticated.
References
Documentation and references used for this lesson.

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