Reputation: 2405
I'm using Inert with Hapi.js and I have a simple directory handler setup that serves a React App:
{
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: '.',
redirectToSlash: true,
index: true,
},
},
}
This works fine when visiting http://localhost:8080. When I add /anything, I get a 404.
How can I get all requests to redirect to the path that's defined? I've read the Inert documentation and tried multiple ideas from the Hapi.js API docs to no avail.
Thanks
Upvotes: 2
Views: 1118
Reputation: 71
I used the onPreResponse
lifecycle hook for Hapi to always send my index.html
when the response is 404
server.ext('onPreResponse', (req, h) => {
const { response } = req;
if (response.isBoom && response.output.statusCode === 404) {
return h.file('index.html');
}
return h.continue;
});
This way it always falls back to my ui, which allows react-router to handle the non-api routes. You can read more about Hapi's lifecycles in the docs.
Upvotes: 7
Reputation: 1364
this is my setup for react serving and working without a problem.
Route config:
{
method: 'GET',
path: '/{param*}',
config: Controller.dashboard
},
Controller:
exports.dashboard = {
auth: false,
description: 'ui build request handler',
handler: async (request, h) => {
return h.file(config.get('uiBuildPath') + 'index.html', {confine: false});
}
};
config.get('uiBuildPath')
is returning the path of my react app build directory in the server. Just this
I put route config to end of my routing definitions, here is exact order. Make sure to put this definition to end
server.route([
{
method: 'GET',
path: '/login',
options: Controller.login
},
{
method: 'GET',
path: '/logout',
options: Controller.logout
},
{
method: 'GET',
path: '/',
config: Controller.dashboard
},
{
method: 'GET',
path: '/{param*}',
config: Controller.dashboard
},
]);
Upvotes: -1