Member-only story
Server-Side Development with Hapi.js — 404 Handling and Shared Methods
3 min readFeb 20, 2021
Hapi.js is a small Node framework for developing back end web apps.
In this article, we’ll look at how to create back end apps with Hapi.js.
404 Handling
We can handle 404 errors easily with Hapi.
For example, we can write:
const Hapi = require('@hapi/hapi');
const Joi = require("@hapi/joi")const init = async () => {
const server = Hapi.server({
port: 3000,
host: '0.0.0.0'
}); server.route({
method: '*',
path: '/{any*}',
handler (request, h) {
return '404 Error! Page Not Found!';
}
}); await server.start();
console.log('Server running on %s', server.info.uri);
};process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});init();
We set the method
to '*'
to allow for all methods.
path
is set to ‘/{any*}’
to allow the route handler to watch for any path.
Server Methods
The server.method
method lets us add methods to our app.