Blog
Microfrontends arquivo

Coisas que (mais cedo ou mais tarde) todo dev frontend vai precisar encarar

Uma lista dos desafios técnicos e conceitos que todo desenvolvedor frontend precisa dominar para escalar aplicações em produção, de feature flags a microfrontends.

No começo, o foco é: HTML, CSS, React, e fazer a tela funcionar.

Mas com o tempo, você percebe que só isso não sustenta um sistema em produção.

Abaixo, uma lista de coisas que ninguém te conta no início, mas que você vai precisar aprender se quiser escalar e manter aplicações reais.

Feature flags

Ligar e desligar funcionalidades em tempo real, sem deploy.

Ferramentas como LaunchDarkly, GrowthBook ou até soluções customizadas com configs por JSON.

Implementação prática

// Feature Flag simples
const useFeatureFlag = (flagName) => {
  const [isEnabled, setIsEnabled] = useState(false);
  
  useEffect(() => {
    fetch(`/api/feature-flags/${flagName}`)
      .then(res => res.json())
      .then(data => setIsEnabled(data.enabled));
  }, [flagName]);
  
  return isEnabled;
};

// Uso no componente
const NewCheckoutFlow = () => {
  const isNewCheckoutEnabled = useFeatureFlag('new-checkout-flow');
  
  return isNewCheckoutEnabled ? <NewCheckout /> : <OldCheckout />;
};

Benefícios

  • Deploy seguro sem risco de quebrar produção
  • Testes A/B em tempo real
  • Rollback instantâneo em caso de problemas
  • Liberação gradual de funcionalidades

Configuração dinâmica

Pare de fazer build a cada alteração.

Use env.js, remote-config.json, Firebase Remote Config ou GrowthBook.

Exemplo com config dinâmica

// config.js - Carregado dinamicamente
window.APP_CONFIG = {
  apiUrl: 'https://api.production.com',
  features: {
    enableAnalytics: true,
    enableChat: false
  },
  limits: {
    maxFileSize: '10MB',
    sessionTimeout: 3600
  }
};

// Uso na aplicação
const config = window.APP_CONFIG || {};
const apiUrl = config.apiUrl || 'http://localhost:3001';

Ferramentas recomendadas

  • Firebase Remote Config - Google
  • GrowthBook - Open source
  • LaunchDarkly - Enterprise
  • Soluções customizadas com JSON/API

CDN e cache

Entenda cache busting, preload, headers, compressão Brotli, CDNs como Cloudflare, CloudFront, ou Fastly.

Estratégias de cache

// Cache busting com versioning
const CACHE_VERSION = 'v1.2.3';
const assetUrl = `/assets/js/app.${CACHE_VERSION}.js`;

// Preload de recursos críticos
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/js/critical.js" as="script">

// Service Worker para cache inteligente
self.addEventListener('fetch', (event) => {
  if (event.request.url.includes('/api/')) {
    event.respondWith(
      caches.open('api-cache').then(cache => {
        return cache.match(event.request).then(response => {
          return response || fetch(event.request).then(fetchResponse => {
            cache.put(event.request, fetchResponse.clone());
            return fetchResponse;
          });
        });
      })
    );
  }
});

Headers importantes

# Cache control
Cache-Control: public, max-age=31536000, immutable

# Compressão
Content-Encoding: br
Content-Type: application/javascript; charset=utf-8

# Segurança
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

Segurança: XSS, CORS, SRI, CSP

Frontend seguro exige:

Sanitização e escape de conteúdo

import DOMPurify from 'dompurify';

// Sanitizar HTML
const cleanHTML = DOMPurify.sanitize(userInput);

// Escape de conteúdo
const escapeHtml = (text) => {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
};

CORS bem definido

// Configuração no backend
app.use(cors({
  origin: ['https://app.example.com', 'https://admin.example.com'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

Subresource Integrity (SRI)

<script 
  src="https://cdn.example.com/library.js"
  integrity="sha384-abc123..."
  crossorigin="anonymous">
</script>

Content Security Policy (CSP)

<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; 
               script-src 'self' 'unsafe-inline' https://trusted-cdn.com;
               style-src 'self' 'unsafe-inline';
               img-src 'self' data: https:;">

Versionamento semântico + release train

Aprenda a usar v1.2.3 corretamente e entenda como empresas organizam entregas em ciclos previsíveis.

Semantic versioning

MAJOR.MINOR.PATCH
1.2.3

MAJOR: Mudanças incompatíveis
MINOR: Funcionalidades compatíveis
PATCH: Correções de bugs

Release train quinzenal

// package.json
{
  "version": "2.1.0",
  "scripts": {
    "release:patch": "npm version patch && npm publish",
    "release:minor": "npm version minor && npm publish",
    "release:major": "npm version major && npm publish"
  }
}

// Release calendar
// Semana 1: Feature freeze
// Semana 2: Testing + Bug fixes
// Semana 3: Release + Deploy
// Semana 4: Planning + Development

Web Vitals

Google mede a performance do seu site com:

Core Web Vitals

// LCP - Largest Contentful Paint
const observer = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  const lastEntry = entries[entries.length - 1];
  console.log('LCP:', lastEntry.startTime);
});
observer.observe({ entryTypes: ['largest-contentful-paint'] });

// CLS - Cumulative Layout Shift
let clsValue = 0;
const clsObserver = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (!entry.hadRecentInput) {
      clsValue += entry.value;
    }
  }
  console.log('CLS:', clsValue);
});
clsObserver.observe({ entryTypes: ['layout-shift'] });

// INP - Interaction to Next Paint
const inpObserver = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log('INP:', entry.processingStart - entry.startTime);
  }
});
inpObserver.observe({ entryTypes: ['event'] });

Ferramentas de monitoramento

  • Lighthouse - Auditoria completa
  • Vercel Analytics - Métricas em tempo real
  • Datadog RUM - Monitoramento contínuo
  • Google PageSpeed Insights - Análise pública

CI/CD e pipelines

Lint, testes, builds, deploys automáticos.

Exemplo com GitHub Actions

name: CI/CD Pipeline

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
      
      - run: npm ci
      - run: npm run lint
      - run: npm run test
      - run: npm run build
      
      - name: Deploy to Production
        if: github.ref == 'refs/heads/main'
        run: npm run deploy

Pipeline stages

  1. Lint - ESLint, Prettier, BiomeJS
  2. Test - Jest, Vitest, Cypress
  3. Build - Webpack, Vite, Rollup
  4. Deploy - Vercel, Netlify, AWS

Monitoramento de erros

Saiba o que está quebrando no cliente.

Sentry integration

import * as Sentry from '@sentry/react';

Sentry.init({
  dsn: 'YOUR_DSN',
  environment: process.env.NODE_ENV,
  tracesSampleRate: 1.0,
});

// Error boundary
<Sentry.ErrorBoundary fallback={ErrorFallback}>
  <App />
</Sentry.ErrorBoundary>

// Custom error tracking
try {
  riskyOperation();
} catch (error) {
  Sentry.captureException(error);
}

Ferramentas recomendadas

  • Sentry - Error tracking completo
  • Datadog RUM - Real User Monitoring
  • New Relic - APM + RUM
  • LogRocket - Session replay
  • TrackJS - JavaScript error tracking

Event tracking e analytics

Ferramentas como PostHog, Amplitude, Plausible ou até um sistema próprio.

PostHog implementation

import posthog from 'posthog-js';

posthog.init('YOUR_API_KEY', {
  api_host: 'https://app.posthog.com',
});

// Track custom events
posthog.capture('button_clicked', {
  button_name: 'signup',
  page: 'homepage'
});

// Feature flags
const isFeatureEnabled = posthog.isFeatureEnabled('new-checkout');

Sistema próprio com Kafka

class EventTracker {
  constructor() {
    this.events = [];
    this.batchSize = 10;
  }
  
  track(event, properties = {}) {
    this.events.push({
      event,
      properties,
      timestamp: Date.now(),
      userId: this.getUserId()
    });
    
    if (this.events.length >= this.batchSize) {
      this.flush();
    }
  }
  
  async flush() {
    if (this.events.length === 0) return;
    
    try {
      await fetch('/api/events', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ events: this.events })
      });
      
      this.events = [];
    } catch (error) {
      console.error('Failed to send events:', error);
    }
  }
}

Micro frontends + design systems

Evite monolitos no frontend.

Arquitetura com Single-SPA

// Shell application
import { registerApplication, start } from 'single-spa';

registerApplication({
  name: 'header',
  app: () => import('@company/header'),
  activeWhen: ['/'],
});

registerApplication({
  name: 'checkout',
  app: () => import('@company/checkout'),
  activeWhen: ['/checkout'],
});

start();

Design system com StencilJS

@Component({
  tag: 'my-button',
  styleUrl: 'my-button.css',
  shadow: true,
})
export class MyButton {
  @Prop() variant: 'primary' | 'secondary' = 'primary';
  @Prop() size: 'small' | 'medium' | 'large' = 'medium';
  @Event() buttonClick: EventEmitter;

  render() {
    return (
      <button 
        class={`btn btn-${this.variant} btn-${this.size}`}
        onClick={() => this.buttonClick.emit()}
      >
        <slot />
      </button>
    );
  }
}

Figma Tokens Studio + Storybook

// tokens.json
{
  "colors": {
    "primary": {
      "500": { "value": "#3B82F6" },
      "600": { "value": "#2563EB" }
    }
  },
  "spacing": {
    "xs": { "value": "4px" },
    "sm": { "value": "8px" }
  }
}

// Storybook stories
export default {
  title: 'Components/Button',
  component: Button,
  parameters: {
    design: {
      type: 'figma',
      url: 'https://figma.com/design/...'
    }
  }
};

Roadmap de aprendizado

Nível iniciante (0-6 meses)

  • HTML, CSS, JavaScript
  • React/Vue/Angular básico
  • Git básico
  • Deploy simples (Vercel/Netlify)

Nível intermediário (6-18 meses)

  • TypeScript
  • Testing (Jest, Cypress)
  • CI/CD básico
  • Performance básica
  • Segurança básica

Nível avançado (18+ meses)

  • Microfrontends
  • Design Systems
  • Monitoramento avançado
  • Arquitetura de sistemas
  • Liderança técnica

Conclusão

Se você está construindo produto digital e quer crescer como dev frontend, guarde essa lista. Comece aos poucos, mas saiba que em algum momento você vai precisar dominar esses pontos.

Prioridades por contexto

Startup/Early Stage:

  1. Feature Flags
  2. Monitoramento de Erros
  3. Web Vitals
  4. CI/CD básico

Scale-up/Growth:

  1. Microfrontends
  2. Design Systems
  3. Event Tracking
  4. Segurança avançada

Enterprise/Large Scale:

  1. Release Trains
  2. Observabilidade completa
  3. Arquitetura distribuída
  4. Governança de código

Este artigo apresenta os desafios que todo desenvolvedor frontend enfrenta ao evoluir na carreira. Para discussões técnicas, implementações ou dúvidas sobre qualquer um desses tópicos, me encontre no LinkedIn ou GitHub.

Me acompanha em eliseu.dev e MFE Brasil Newsletter: sempre compartilho conteúdo técnico e prático sobre arquitetura de frontend.

esc
  • Home Início
  • Sobre Trajetória e como trabalho
  • Blog Artigos sobre IA, plataforma e liderança
  • Projetos Demos públicos de frontend com IA
  • Currículo Web, PDF, Markdown e texto
  • Setup Hardware e ferramentas
  • Inference hooks do Claude: se o seu servidor de política cair, quem decide é um checkbox Arquitetura
  • Claude Code vazava o e-mail no User-Agent: o que eu checaria amanhã Segurança
  • Sete fases e onze testes: como a tela do agente aguenta queda, pausa e falta de rede Arquitetura
  • RAG no navegador custa 23 MB de download: como eu decidiria entre WebGPU e backend Arquitetura
↑↓ navegar ↵ abrir esc fechar