refine nginx caching strategy and add service worker update prompt with periodic checks
Some checks failed
Build and Push Docker Images / build-backend (push) Has been cancelled
Build and Push Docker Images / build-frontend (push) Has been cancelled

This commit is contained in:
Egor Pozharov
2026-04-21 12:55:01 +06:00
parent 60dea22ced
commit 4110083019
6 changed files with 96 additions and 16 deletions

View File

@@ -10,12 +10,45 @@ server {
gzip_min_length 1024; gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json; gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
# Cache static assets # Hashed build assets — safe to cache forever
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { location /assets/ {
expires 1y; expires 1y;
add_header Cache-Control "public, immutable"; add_header Cache-Control "public, immutable";
} }
# Other static files (icons, fonts at root etc.) — short cache
location ~* \.(png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot)$ {
expires 7d;
add_header Cache-Control "public, max-age=604800";
}
# Never cache entry points — must always revalidate so clients
# can detect new frontend versions and service worker updates
location = /index.html {
add_header Cache-Control "no-cache, no-store, must-revalidate";
expires 0;
}
location = /sw.js {
add_header Cache-Control "no-cache, no-store, must-revalidate";
expires 0;
}
location = /registerSW.js {
add_header Cache-Control "no-cache, no-store, must-revalidate";
expires 0;
}
location = /manifest.webmanifest {
add_header Cache-Control "no-cache, no-store, must-revalidate";
expires 0;
}
location = /manifest.json {
add_header Cache-Control "no-cache, no-store, must-revalidate";
expires 0;
}
# Proxy API requests to backend # Proxy API requests to backend
location /api/ { location /api/ {
proxy_pass http://backend:8080; proxy_pass http://backend:8080;

View File

@@ -4,6 +4,7 @@ import { DeliveryForm } from './components/delivery/DeliveryForm';
import { LoginForm } from './components/auth/LoginForm'; import { LoginForm } from './components/auth/LoginForm';
import { ToastContainer } from './components/ui/Toast'; import { ToastContainer } from './components/ui/Toast';
import { Button } from './components/ui/Button'; import { Button } from './components/ui/Button';
import { UpdatePrompt } from './components/ui/UpdatePrompt';
import { useDeliveryStore } from './stores/deliveryStore'; import { useDeliveryStore } from './stores/deliveryStore';
import { useAuthStore } from './stores/authStore'; import { useAuthStore } from './stores/authStore';
@@ -89,6 +90,7 @@ function App() {
if (!isAuthenticated) { if (!isAuthenticated) {
return ( return (
<> <>
<UpdatePrompt />
<LoginForm /> <LoginForm />
<ToastContainer /> <ToastContainer />
</> </>
@@ -97,6 +99,7 @@ function App() {
return ( return (
<div className="min-h-screen bg-[#fbf8fb]"> <div className="min-h-screen bg-[#fbf8fb]">
<UpdatePrompt />
<header className="sticky top-0 z-40 bg-[#1B263B] text-white shadow-md"> <header className="sticky top-0 z-40 bg-[#1B263B] text-white shadow-md">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-14"> <div className="flex items-center justify-between h-14">

View File

@@ -0,0 +1,55 @@
import { useRegisterSW } from 'virtual:pwa-register/react';
import { RefreshCw } from 'lucide-react';
import { Button } from './Button';
// Check for SW updates every hour and on tab focus/visibility change
const UPDATE_INTERVAL_MS = 60 * 60 * 1000;
export function UpdatePrompt() {
const {
needRefresh: [needRefresh],
updateServiceWorker,
} = useRegisterSW({
onRegisteredSW(_swUrl, registration) {
if (!registration) return;
const checkForUpdate = async () => {
if (registration.installing || !navigator) return;
if ('connection' in navigator && !navigator.onLine) return;
try {
await registration.update();
} catch {
// network error — ignore, will retry
}
};
setInterval(checkForUpdate, UPDATE_INTERVAL_MS);
const onVisible = () => {
if (document.visibilityState === 'visible') checkForUpdate();
};
document.addEventListener('visibilitychange', onVisible);
window.addEventListener('focus', checkForUpdate);
},
});
if (!needRefresh) return null;
return (
<div className="fixed top-0 inset-x-0 z-[60] bg-[#1B263B] text-white shadow-lg">
<div className="max-w-7xl mx-auto px-4 py-2 flex items-center justify-between gap-3">
<div className="flex items-center gap-2 text-sm">
<RefreshCw size={16} className="shrink-0" />
<span>Доступна новая версия приложения</span>
</div>
<Button
size="sm"
onClick={() => updateServiceWorker(true)}
className="bg-white text-[#1B263B] hover:bg-white/90"
>
Обновить
</Button>
</div>
</div>
);
}

View File

@@ -3,18 +3,6 @@ import { createRoot } from 'react-dom/client'
import './index.css' import './index.css'
import App from './App.tsx' import App from './App.tsx'
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
.then((registration) => {
console.log('SW registered:', registration)
})
.catch((error) => {
console.log('SW registration failed:', error)
})
})
}
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
<App /> <App />

View File

@@ -5,7 +5,7 @@
"useDefineForClassFields": true, "useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"], "lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext", "module": "ESNext",
"types": ["vite/client"], "types": ["vite/client", "vite-plugin-pwa/client", "vite-plugin-pwa/react"],
"skipLibCheck": true, "skipLibCheck": true,
/* Bundler mode */ /* Bundler mode */

View File

@@ -9,10 +9,11 @@ export default defineConfig({
react(), react(),
tailwindcss(), tailwindcss(),
VitePWA({ VitePWA({
registerType: 'autoUpdate', registerType: 'prompt',
manifest: false, // manifest.json from public manifest: false, // manifest.json from public
workbox: { workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,json}'], globPatterns: ['**/*.{js,css,html,ico,png,svg,json}'],
cleanupOutdatedCaches: true,
runtimeCaching: [ runtimeCaching: [
{ {
urlPattern: /^https:\/\/.*\/api\//, urlPattern: /^https:\/\/.*\/api\//,