Skip to content

Instantly share code, notes, and snippets.

@yjwong
Created April 15, 2023 04:31
Show Gist options
  • Save yjwong/24c814dd444e79f3ce3845c56264ef3a to your computer and use it in GitHub Desktop.
Save yjwong/24c814dd444e79f3ce3845c56264ef3a to your computer and use it in GitHub Desktop.
Redirect missing Webpack assets to S3 bucket
import * as path from 'path';
import * as Boom from '@hapi/boom';
import { plugin as H2O2 } from '@hapi/h2o2';
import * as Hapi from '@hapi/hapi';
export interface WebpackAssetsPluginOptions {
bundleStore: {
enabled: boolean;
uri: string;
};
}
const WebpackAssetsPlugin: Hapi.Plugin<WebpackAssetsPluginOptions> &
Hapi.PluginNameVersion = {
name: 'WebpackAssetsPlugin',
async register(server, options) {
const routePath = '/assets/{param*}';
server.route({
method: 'GET',
path: '/assets/{param*}',
handler: {
directory: {
path: path.join(__dirname, '..', '..', '..', 'dist', 'assets'),
},
},
});
if (options.bundleStore.enabled) {
server.ext('onPreResponse', (request, h) => {
if (request.route.path !== routePath) {
return h.continue;
}
if (
Boom.isBoom(request.response) &&
request.response.output.statusCode === 404
) {
return h.proxy({
passThrough: true,
uri: options.bundleStore.uri,
xforward: true,
});
}
return h.continue;
});
}
},
dependencies: [H2O2.pkg.name],
};
export { WebpackAssetsPlugin };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment