How to make redirect in Hapi


hapi nodejs Tutorials

This tutorial is compatible with Hapi v17.8.1
To create a simple redirect we can use the .redirect() method in the handler of route. This method takes a relative or an absolute URI used to redirect the client to the passed resource. It sets the 302 HTTP redirection:

server.route({
    method: 'GET',
    path: '/redirect',
    handler: (request, reply) => {
        return reply.redirect('https://akhromieiev.com');
    }
});

Also, the second way to set the 302 redirect:

server.route({
    method: 'GET',
    path: '/redirect',
    handler: (request, reply) => {
        return reply.redirect('https://akhromieiev.com').temporary();
    }
});

The 301 or permanent redirect you can make in two ways:

server.route({
    method: 'GET',
    path: '/redirect',
    handler: (request, reply) => {
        return reply.redirect('https://akhromieiev.com').code(301);
    }
});

OR using the* .permanent* method:

server.route({
    method: 'GET',
    path: '/redirect',
    handler: (request, reply) => {
        return reply.redirect('https://akhromieiev.com').permanent();
    }
});

The full example of server:

'use strict';

const Hapi = require('hapi');

const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});

server.route({
    method: 'GET',
    path: '/temporary',
    handler: (request, reply) => {
        return reply.redirect('https://akhromieiev.com').temporary();
    }
});

server.route({
    method: 'GET',
    path: '/permanent',
    handler: (request, reply) => {
        return reply.redirect('https://akhromieiev.com').permanent();
    }
});

const init = async () => {
    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

Learning Hapi.js? Buy my Hapi.js Handbook🔥

comments powered by Disqus