npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@agenus-io/web-push

v0.0.1

Published

React hook para gerenciar notificações push com service worker

Readme

@agenus-io/web-push

React hook para gerenciar notificações push com service worker.

Instalação

npm install @agenus-io/web-push
# ou
pnpm add @agenus-io/web-push
# ou
yarn add @agenus-io/web-push

Requisitos

  • React >= 16.8.0
  • Navegador com suporte a Service Workers e Push API

Uso Básico

import { usePush } from "@agenus-io/web-push";

function App() {
  const { isSupported, isChecking, error, subscription, requestPermission } =
    usePush({
      apiKey: "sua-chave-publica-vapid",
    });

  if (isChecking) {
    return <div>Verificando suporte...</div>;
  }

  if (!isSupported) {
    return <div>Seu navegador não suporta notificações push</div>;
  }

  return (
    <div>
      {error && <p>Erro: {error}</p>}
      {!subscription && (
        <button onClick={requestPermission}>
          Ativar Notificações Push
        </button>
      )}
      {subscription && <p>Notificações ativadas!</p>}
    </div>
  );
}

Service Worker

O pacote automaticamente copia o service worker (sw.js) para a pasta public/ do seu projeto durante a instalação. Se você precisar usar um caminho customizado:

const { subscription } = usePush({
  apiKey: "sua-chave-publica-vapid",
  serviceWorkerPath: "/custom-path/sw.js", // Caminho customizado
});

API

usePush(options)

Hook principal para gerenciar notificações push.

Parâmetros

  • apiKey (string, obrigatório): Chave pública VAPID para autenticação
  • serviceWorkerPath (string, opcional): Caminho customizado para o service worker. Padrão: /sw.js

Retorno

  • isSupported (boolean): Indica se o navegador suporta notificações push
  • isChecking (boolean): Indica se está verificando o suporte
  • error (string | null): Mensagem de erro, se houver
  • subscription (PushSubscription | null): Objeto de assinatura push
  • requestPermission(): Função para solicitar permissão de notificação
  • subscribeToPush(): Função para inscrever-se nas notificações push

Exemplo Completo

import { usePush } from "@agenus-io/web-push";
import { useEffect } from "react";

function NotificationButton() {
  const {
    isSupported,
    isChecking,
    error,
    subscription,
    requestPermission,
    subscribeToPush,
  } = usePush({
    apiKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || "",
  });

  useEffect(() => {
    if (subscription) {
      // Enviar subscription para seu backend
      fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(subscription),
      });
    }
  }, [subscription]);

  if (isChecking) return <div>Carregando...</div>;
  if (!isSupported) return <div>Não suportado</div>;

  return (
    <div>
      {error && <p className="error">{error}</p>}
      {!subscription ? (
        <button onClick={requestPermission}>Ativar Notificações</button>
      ) : (
        <p>✓ Notificações ativadas</p>
      )}
    </div>
  );
}

Enviando Notificações

Para enviar notificações push, você precisa de um servidor backend que use a chave privada VAPID. O service worker incluído no pacote suporta o seguinte formato de payload:

{
  "title": "Título da Notificação",
  "body": "Corpo da mensagem",
  "icon": "/icon.png",
  "badge": "/badge.png",
  "image": "/image.png",
  "url": "/redirect-url",
  "vibrate": [200, 100, 200],
  "actions": [
    {
      "action": "action1",
      "title": "Ação 1",
      "icon": "/action1-icon.png",
      "url": "/action1-url"
    }
  ],
  "data": {
    "custom": "data"
  }
}

Desenvolvimento

# Instalar dependências
pnpm install

# Build
pnpm build

# Desenvolvimento com watch
pnpm dev

# Lint
pnpm lint

# Format
pnpm format

Publicação

Este projeto usa Changesets para gerenciar versões e changelogs.

Processo de Publicação

  1. Criar um changeset (após fazer suas mudanças):

    pnpm changeset

    Isso criará um arquivo em .changeset/ descrevendo suas mudanças. Escolha o tipo de versão (patch, minor, major).

  2. Commit e push:

    git add .
    git commit -m "feat: sua mudança"
    git push
  3. Publicar:

    pnpm publish

    Ou use o script helper:

    node scripts/publish.js

    O script irá:

    • Verificar se você está logado no npm
    • Fazer build do projeto
    • Aplicar as versões do changeset
    • Publicar no npm

Scripts Disponíveis

  • pnpm changeset - Criar um novo changeset
  • pnpm changeset:version - Aplicar versões dos changesets
  • pnpm changeset:publish - Publicar no npm
  • pnpm publish - Script completo de publicação (recomendado)

Primeira Publicação

Antes da primeira publicação, certifique-se de:

  1. Estar logado no npm com acesso à organização @agenus-io:

    npm login --scope=@agenus-io
  2. Ter configurado o registry correto no .npmrc (se necessário)

Nota: O pacote é publicado como público automaticamente (não requer plano pago). O script já inclui --access public.

Licença

ISC