To handle the issue of 404 errors after publishing your Inertia app with Laravel Breeze and Vite, you can implement a mechanism to detect when the assets have changed and prompt the user to refresh the page. This can be achieved by using a combination of versioning and a service worker or a simple JavaScript check.
Here's a step-by-step solution:
-
Versioning the Assets: Ensure that Vite is configured to version your assets. This is typically done by default, but you can double-check your
vite.config.js:export default { build: { manifest: true, rollupOptions: { output: { entryFileNames: 'assets/[name].[hash].js', chunkFileNames: 'assets/[name].[hash].js', assetFileNames: 'assets/[name].[hash].[ext]' } } } } -
Creating a Version Endpoint: Create an endpoint in your Laravel application that returns the current version of your assets. You can store the version in a file or an environment variable. For simplicity, let's use an environment variable.
In your
.envfile, add:ASSET_VERSION=1.0.0Then, create a route and controller method to return this version:
// routes/web.php Route::get('/asset-version', function () { return response()->json(['version' => env('ASSET_VERSION')]); }); -
Checking for Version Changes: Use JavaScript to periodically check the version endpoint and compare it with the current version. If the version has changed, prompt the user to refresh the page.
let currentVersion = '1.0.0'; // This should match the initial version in your .env file async function checkForAssetUpdates() { try { const response = await fetch('/asset-version'); const data = await response.json(); if (data.version !== currentVersion) { alert('A new version of the site is available. Please refresh the page.'); currentVersion = data.version; } } catch (error) { console.error('Error checking for asset updates:', error); } } // Check for updates every 5 minutes setInterval(checkForAssetUpdates, 300000); -
Updating the Version on Deploy: Ensure that you update the
ASSET_VERSIONin your.envfile each time you deploy a new version of your app. This can be automated in your deployment script.For example, in your deployment script, you could increment the version number:
# Increment the version number (this is a simple example, you might want to use a more sophisticated versioning strategy) CURRENT_VERSION=$(grep ASSET_VERSION .env | cut -d '=' -f2) NEW_VERSION=$(echo $CURRENT_VERSION | awk -F. -v OFS=. '{$NF += 1 ; print}') sed -i "s/ASSET_VERSION=$CURRENT_VERSION/ASSET_VERSION=$NEW_VERSION/" .env # Continue with your deployment steps...
By implementing these steps, you can detect when the assets have changed and prompt the user to refresh the page, ensuring that they always have the latest version of your app.