Programação

PWA: Progressive Web Apps - O Futuro dos Aplicativos

Descubra PWAs: o que são, vantagens sobre apps nativos, como criar, service workers, offline-first e casos de sucesso.

PWA: Progressive Web Apps - O Melhor dos Dois Mundos

Progressive Web Apps representam uma das maiores evoluções da plataforma web: aplicações que rodam no navegador mas oferecem experiência idêntica a apps nativos. Elas podem ser instaladas na tela inicial do celular, funcionam offline, enviam push notifications e carregam quase instantâneamente. O Twitter Lite como PWA reduziu o consumo de dados em 70% e aumentou tweets enviados em 75%. A Starbucks viu pedidos dobrárem após lançar seu PWA.

Neste guia completo, você aprenderá a criar PWAs do zero, desde o Web App Manifest e Service Workers até funcionalidades avançadas como Background Sync, Push Notifications, cache inteligente com Workbox e publicação.

O Que É PWA?

PWA é uma aplicação web que utiliza tecnologias modernas do browser — Service Workers, Web App Manifest e APIs avançadas — para proporcionar uma experiência indistinguível de apps nativos. A grande vantagem sobre apps tradicionais é que PWAs não precisam ser publicadas em app stores: os usuários acessam via URL e podem instalar diretamente do navegador, eliminando a fricção de download.

Características

  • 📱 Instalável - Adicionar à tela inicial
  • 🔌 Offline-first - Funciona sem internet
  • 🚀 Rápido - Cache inteligente
  • 🔔 Push notifications - Engajamento
  • 📲 App-like - Experiência nativa
  • 🔒 Seguro - HTTPS obrigatório

Exemplos Famosos

  • Twitter Lite
  • Pinterest
  • Starbucks
  • Uber
  • Spotify Web

Requisitos de um PWA

Para que um site seja classificado como PWA pelos navegadores (e receba o prompt de instalação), ele precisa atender a quatro requisitos técnicos fundamentais. Estes não são opcionais — sem eles, o browser simplesmente não reconhece sua aplicação como PWA.

1. HTTPS

PWA requer HTTPS (exceto localhost)

Razões:
- Service Workers só funcionam em HTTPS
- Segurança de dados
- Confiança do usuário

2. Service Worker

// Intercepta requisições de rede
// Gerencia cache
// Habilita funcionalidade offline

3. Web App Manifest

// Define como o app aparece quando instalado
// Ícones, cores, orientação, etc

4. Responsivo

Funciona em qualquer tamanho de tela
Mobile-first design

Web App Manifest

O manifest.json é o ‘cartão de identidade’ do seu PWA. Ele define como a aplicação aparece quando instalada: nome, ícones para diferentes tamanhos de tela, cores da interface, orientação preferida, URL de início e modo de exibição (standalone para parecer um app nativo, ou fullscreen para jogos). Sem um manifest válido, o navegador não oferece a opção de instalação.

manifest.json

{
  "name": "Meu App PWA",
  "short_name": "MeuApp",
  "description": "Um Progressive Web App incrível",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#2196f3",
  "orientation": "portrait-primary",
  "icons": [
    {
      "src": "/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "/icons/icon-96x96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "screenshots": [
    {
      "src": "/screenshots/home.png",
      "sizes": "540x720",
      "type": "image/png"
    },
    {
      "src": "/screenshots/detail.png",
      "sizes": "540x720",
      "type": "image/png"
    }
  ],
  "categories": ["productivity", "utilities"],
  "shortcuts": [
    {
      "name": "Nova Tarefa",
      "short_name": "Nova",
      "description": "Criar nova tarefa",
      "url": "/new",
      "icons": [{ "src": "/icons/new.png", "sizes": "96x96" }]
    }
  ]
}

Incluir no HTML

<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Meu PWA</title>
  
  <!-- Manifest -->
  <link rel="manifest" href="/manifest.json">
  
  <!-- Theme color -->
  <meta name="theme-color" content="#2196f3">
  
  <!-- iOS -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="MeuApp">
  <link rel="apple-touch-icon" href="/icons/icon-152x152.png">
  
  <!-- MS -->
  <meta name="msapplication-TileImage" content="/icons/icon-144x144.png">
  <meta name="msapplication-TileColor" content="#2196f3">
</head>
<body>
  <!-- App content -->
</body>
</html>

Service Worker

O Service Worker é o coração de todo PWA — um script JavaScript que roda em segundo plano, separado da página web, atuando como proxy entre a aplicação e a rede. Ele intercepta todas as requisições de rede e decide se serve do cache ou busca na internet, habilitando funcionalidade offline. Além disso, Service Workers possibilitam push notifications e background sync, funcionalidades antes exclusivas de apps nativos.

O ciclo de vida do Service Worker segue três estágios: Install (cacheia recursos essenciais), Activate (limpa caches antigos) e Fetch (intercepta requisições e serve do cache ou rede). Entender esse ciclo é fundamental para implementar caching correto.

Registrar Service Worker

// app.js
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then(registration => {
        console.log('SW registered:', registration);
      })
      .catch(error => {
        console.log('SW registration failed:', error);
      });
  });
}

Service Worker Básico

// sw.js
const CACHE_NAME = 'my-pwa-v1';
const urlsToCache = [
  '/',
  '/index.html',
  '/styles.css',
  '/app.js',
  '/offline.html'
];

// Install - cachear recursos
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        console.log('Cache opened');
        return cache.addAll(urlsToCache);
      })
  );
});

// Activate - limpar caches antigos
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== CACHE_NAME) {
            console.log('Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

// Fetch - servir do cache
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Cache hit
        if (response) {
          return response;
        }
        
        // Fetch from network
        return fetch(event.request);
      })
  );
});

Estratégias de Cache

A escolha da estratégia de cache correta é crucial para o comportamento do PWA. Cada estratégia tem trade-offs entre velocidade (servir do cache) e frescor (buscar da rede). A estratégia ideal depende do tipo de recurso: imagens e CSS raramente mudam (cache first), APIs precisam de dados frescos (network first), e conteúdo semi-estático se beneficia de stale-while-revalidate (retorna cache imediatamente e atualiza em background).

1. Cache First (Offline First)

// Tenta cache primeiro, depois rede
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

2. Network First

// Tenta rede primeiro, fallback para cache
self.addEventListener('fetch', event => {
  event.respondWith(
    fetch(event.request)
      .catch(() => caches.match(event.request))
  );
});

3. Stale While Revalidate

// Retorna cache e atualiza em background
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.open(CACHE_NAME).then(cache => {
      return cache.match(event.request).then(response => {
        const fetchPromise = fetch(event.request).then(networkResponse => {
          cache.put(event.request, networkResponse.clone());
          return networkResponse;
        });
        
        return response || fetchPromise;
      });
    })
  );
});

4. Cache Only

// Apenas cache (para assets estáticos)
self.addEventListener('fetch', event => {
  event.respondWith(caches.match(event.request));
});

5. Network Only

// Apenas rede (para dados sempre frescos)
self.addEventListener('fetch', event => {
  event.respondWith(fetch(event.request));
});

Workbox (Biblioteca Google)

Workbox é uma biblioteca do Google que simplifica drasticamente a criação de Service Workers. Em vez de escrever toda a lógica de caching manualmente, Workbox fornece estratégias prontas (CacheFirst, NetworkFirst, StaleWhileRevalidate), gerenciamento automático de precache, expiração configurável e versionamento de cache. É a ferramenta recomendada pelo próprio Google para PWAs em produção.

Instalação

npm install workbox-cli --global

Configuração

// workbox-config.js
module.exports = {
  globDirectory: 'dist/',
  globPatterns: [
    '**/*.{html,js,css,png,jpg,json}'
  ],
  swDest: 'dist/sw.js',
  runtimeCaching: [
    {
      urlPattern: /^https:\/\/api\.example\.com/,
      handler: 'NetworkFirst',
      options: {
        cacheName: 'api-cache',
        expiration: {
          maxEntries: 50,
          maxAgeSeconds: 300
        }
      }
    },
    {
      urlPattern: /\.(?:png|jpg|jpeg|svg|gif)$/,
      handler: 'CacheFirst',
      options: {
        cacheName: 'image-cache',
        expiration: {
          maxEntries: 100,
          maxAgeSeconds: 30 * 24 * 60 * 60 // 30 dias
        }
      }
    }
  ]
};

Gerar Service Worker

workbox generateSW workbox-config.js

Service Worker com Workbox

// sw.js
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js');

// Precache
workbox.precaching.precacheAndRoute([
  { url: '/', revision: '1' },
  { url: '/styles.css', revision: '1' },
  { url: '/app.js', revision: '1' }
]);

// Runtime caching
workbox.routing.registerRoute(
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'images',
    plugins: [
      new workbox.expiration.ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60
      })
    ]
  })
);

workbox.routing.registerRoute(
  /^https:\/\/api\.example\.com/,
  new workbox.strategies.NetworkFirst({
    cacheName: 'api',
    plugins: [
      new workbox.expiration.ExpirationPlugin({
        maxEntries: 50,
        maxAgeSeconds: 5 * 60
      })
    ]
  })
);

Funcionalidades Avançadas

Além de cache offline, PWAs modernos suportam funcionalidades antes exclusivas de apps nativos: Background Sync permite enviar dados quando a conexão é restaurada (ideal para formulários offline), Push Notifications engajam usuários mesmo com o app fechado, e o Install Prompt permite uma experiência de instalação customizada e elegante.

1. Background Sync

// Registrar sync
navigator.serviceWorker.ready.then(registration => {
  return registration.sync.register('sync-posts');
});

// Service Worker
self.addEventListener('sync', event => {
  if (event.tag === 'sync-posts') {
    event.waitUntil(syncPosts());
  }
});

async function syncPosts() {
  const posts = await getPostsFromIndexedDB();
  
  for (const post of posts) {
    try {
      await fetch('/api/posts', {
        method: 'POST',
        body: JSON.stringify(post)
      });
      await deletePostFromIndexedDB(post.id);
    } catch (error) {
      console.error('Sync failed:', error);
    }
  }
}

2. Push Notifications

// Pedir permissão
async function requestNotificationPermission() {
  const permission = await Notification.requestPermission();
  
  if (permission === 'granted') {
    const registration = await navigator.serviceWorker.ready;
    const subscription = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: 'YOUR_PUBLIC_KEY'
    });
    
    // Enviar subscription para servidor
    await fetch('/api/subscribe', {
      method: 'POST',
      body: JSON.stringify(subscription)
    });
  }
}

// Service Worker - receber push
self.addEventListener('push', event => {
  const data = event.data.json();
  
  const options = {
    body: data.body,
    icon: '/icons/icon-192x192.png',
    badge: '/icons/badge-72x72.png',
    vibrate: [200, 100, 200],
    data: {
      url: data.url
    }
  };
  
  event.waitUntil(
    self.registration.showNotification(data.title, options)
  );
});

// Clicar na notificação
self.addEventListener('notificationclick', event => {
  event.notification.close();
  
  event.waitUntil(
    clients.openWindow(event.notification.data.url)
  );
});

3. Offline Page

// Service Worker
const OFFLINE_URL = '/offline.html';

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.add(OFFLINE_URL))
  );
});

self.addEventListener('fetch', event => {
  if (event.request.mode === 'navigate') {
    event.respondWith(
      fetch(event.request)
        .catch(() => caches.match(OFFLINE_URL))
    );
  }
});
<!-- offline.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Offline</title>
  <style>
    body {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
      font-family: sans-serif;
      text-align: center;
    }
  </style>
</head>
<body>
  <div>
    <h1>🔌 Você está offline</h1>
    <p>Verifique sua conexão e tente novamente.</p>
    <button onclick="location.reload()">Tentar Novamente</button>
  </div>
</body>
</html>

4. Install Prompt

let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevenir prompt automático
  e.preventDefault();
  
  // Guardar evento
  deferredPrompt = e;
  
  // Mostrar botão de instalação
  document.getElementById('install-button').style.display = 'block';
});

document.getElementById('install-button').addEventListener('click', async () => {
  if (deferredPrompt) {
    // Mostrar prompt
    deferredPrompt.prompt();
    
    // Aguardar escolha do usuário
    const { outcome } = await deferredPrompt.userChoice;
    
    console.log(`User response: ${outcome}`);
    
    // Limpar
    deferredPrompt = null;
    document.getElementById('install-button').style.display = 'none';
  }
});

// Detectar quando instalado
window.addEventListener('appinstalled', () => {
  console.log('PWA installed');
  deferredPrompt = null;
});

IndexedDB para Armazenamento

// Abrir banco
const request = indexedDB.open('MyDatabase', 1);

request.onupgradeneeded = (event) => {
  const db = event.target.result;
  
  // Criar object store
  const objectStore = db.createObjectStore('posts', { keyPath: 'id', autoIncrement: true });
  
  // Criar índices
  objectStore.createIndex('title', 'title', { unique: false });
  objectStore.createIndex('date', 'date', { unique: false });
};

request.onsuccess = (event) => {
  const db = event.target.result;
  
  // Adicionar dados
  const transaction = db.transaction(['posts'], 'readwrite');
  const objectStore = transaction.objectStore('posts');
  
  objectStore.add({
    title: 'Meu Post',
    content: 'Conteúdo...',
    date: new Date()
  });
  
  // Ler dados
  const getRequest = objectStore.get(1);
  getRequest.onsuccess = () => {
    console.log(getRequest.result);
  };
};

Testing PWA

Lighthouse

# Chrome DevTools
1. Abrir DevTools (F12)
2. Aba "Lighthouse"
3. Selecionar "Progressive Web App"
4. Clicar "Generate report"

PWA Builder

https://www.pwabuilder.com/

1. Inserir URL do site
2. Analisar PWA
3. Ver sugestões de melhorias
4. Gerar packages para stores

Deploy

Vercel

# Instalar CLI
npm i -g vercel

# Deploy
vercel --prod

Netlify

# Instalar CLI
npm install -g netlify-cli

# Deploy
netlify deploy --prod

Melhores Práticas

1. App Shell Architecture

Cachear estrutura do app (shell)
Carregar conteúdo dinamicamente
Experiência instantânea

2. Lazy Loading

// Carregar recursos sob demanda
const image = new Image();
image.src = '/large-image.jpg';

3. Otimizar Assets

- Comprimir imagens (WebP)
- Minificar JS/CSS
- Code splitting
- Tree shaking

4. HTTPS Sempre

PWA requer HTTPS
Use Let's Encrypt (grátis)

Conclusão

PWAs representam o futuro das aplicações web, combinando o alcance universal da web com a experiência rica de apps nativos. Com Service Workers para cache inteligente e funcionalidade offline, Web App Manifest para instalação, Push Notifications para engajamento e Workbox para simplificar o desenvolvimento, criar um PWA profissional nunca foi tão acessível.

A tendência é clara: cada vez mais empresas estão adotando PWAs como alternativa (ou complemento) a apps nativos, especialmente em mercados emergentes onde banda larga limitada e dispositivos de entrada tornam a eficiência do PWA uma vantagem competitiva decisiva.

Principais Vantagens:

  • 📱 Instalável
  • 🔌 Funciona offline
  • 🚀 Performance nativa
  • 💰 Custo reduzido
  • 🌍 Alcance universal

Quer transformar seu site em PWA? A HG Soluções pode desenvolver Progressive Web Apps completos.

Entre em contato: https://hgsolucoes.com