I realize now this has been discussed already and with much more technical attempts compared to mine. It seems it’s not really ideal to use Vapor if I’m set on keeping PWA functionality.
Using ServiceWorkers with Laravel Vapor
I use the package silviolleite/laravelpwa to load my project as a progressive web app (mostly for appearance on mobile when saved to the Homescreen). I'm trying to move my project to Laravel Vapor, and the during deployment the serviceworker.js is moved from the public folder to the assets folder in AWS S3 (automatically for those not familiar with Vapor).
I've tried the following workarounds.
For reference, the package inserts the following into the page <head> tag:
<script type="text/javascript">
// Initialize the service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceworker.js', {
scope: '.'
}).then(function (registration) {
// Registration was successful
console.log('Laravel PWA: ServiceWorker registration successful with scope: ', registration.scope);
}, function (err) {
// registration failed :(
console.log('Laravel PWA: ServiceWorker registration failed: ', err);
});
}
</script>
This is not allowed, because it is an external file:
<script type="text/javascript">
// Initialize the service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register({{ env('ASSET_URL') . '/servicesworkder.js' }}, {
scope: '.'
}).then(function (registration) {
// Registration was successful
console.log('Laravel PWA: ServiceWorker registration successful with scope: ', registration.scope);
}, function (err) {
// registration failed :(
console.log('Laravel PWA: ServiceWorker registration failed: ', err);
});
}
</script>
And redirects are not allowed.
Route::redirect('/servicesworker.js', env('ASSET_URL') . '/serviceworker.js');
I've also tried to return the asset as a file and I get a FileNotFound error.
Route::get('/serviceworker.js', function() {
return response()->file(env('ASSET_URL') . '/serviceworker.js');
});
// returns a message like the following
the file "https://...asset_url.../serviceworker.js" cannot be found.
Any suggestions on how I could get this to work?
After contacting Vapor support I got the following code for linking to the serviceworker.js asset and it works perfectly!
Route::get('/serviceworker.js', function () {
return response(file_get_contents(asset('/serviceworker.js')), 200, [
'Content-Type' => 'text/javascript',
'Cache-Control' => 'public, max-age=3600',
]);
});
Please or to participate in this conversation.