Member-only story

Server-Side Development with Hapi.js — Caching and Cookie

John Au-Yeung
3 min readFeb 19, 2021

--

Photo by Christina Branco on Unsplash

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.

Caching

We can control caching by setting some properties in our routes.

For example, we can write:

const Hapi = require('@hapi/hapi');const init = async () => {  const server = Hapi.server({
port: 3000,
host: '0.0.0.0'
});
server.route({
path: '/{ttl?}',
method: 'GET',
handler(request, h) {
const response = h.response({
hello: 'world'
});
if (request.params.ttl) {
response.ttl(request.params.ttl);
}
return response;
},
options: {
cache: {
expiresIn: 30 * 1000,
privacy: 'private'
}
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();

We call the route with server.route .

Then we call response.ttl to set the duration of the caching of the response.

--

--

No responses yet