The Hapi.js framework, commonly associated with "Hapi CLI" in a general sense (though a dedicated `hapi-cli` for route management isn't a standard or widely used tool), defines its routes programmatically within the application code, not typically via a command-line `route add` instruction. There isn't a standard, officially supported 'Hapi CLI' command named `route add` that would dynamically modify a running Hapi server's routing table from the command line.
Hapi.js routes are configured directly in your JavaScript application files using the `server.route()` method. This allows for rich configuration including path, method, handler function, validation, authentication, and more.
Rather than a CLI command, you would define routes in your Hapi application code, typically in a file like `index.js`, `server.js`, or within a plugin.
**Syntax Example (within JavaScript application code):**
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
// Define a GET route
server.route({
method: 'GET',
path: '/hello',
handler: (request, h) => {
return 'Hello, Hapi!';
}
});
// Define a POST route with parameters
server.route({
method: 'POST',
path: '/users/{id}',
handler: (request, h) => {
const userId = request.params.id;
return `Creating user with ID: ${userId}`;
}
});
// Define a route that returns JSON
server.route({
method: 'GET',
path: '/data',
handler: (request, h) => {
return { message: 'This is some data', timestamp: new Date() };
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();**Explanation:**
* **`server.route(options)`**: This is the core method for defining a single route.
* **`options` Object**: An object containing the route configuration.
* **`method`**: The HTTP method(s) this route will respond to (e.g., `'GET'`, `'POST'`, `'PUT'`, `'DELETE'`, `'*'` for all methods, or an array of methods `['GET', 'HEAD']`).
* **`path`**: The URL path for the route. This can include parameters (e.g., `/users/{id}`) or wildcards.
* **`handler`**: A function that will be executed when the route matches an incoming request. It receives `request` and `h` (response toolkit) arguments and should return a value (which becomes the response payload) or a Promise that resolves to a value.
If you were thinking of a `cli` tool to *generate* route boilerplate or scaffolding for a Hapi application, tools like `hatch-cli` (a community-driven project, not officially part of Hapi.js core) might offer commands like `hatch generate route <name>`, but these are typically for file generation, not runtime route manipulation.