9+

next-push

A modern, lightweight push notification library for Next.js applications.

Live Demo

Supported
No
Permission
default

Push Notifications Not Supported

This browser doesn't support push notifications.

Active Subscriptions

0 subscriptions
📱

No Subscriptions Yet

Start by subscribing above

Quick Start

Get started with Next-Push in just a few steps.

1. Install the package

npm install next-push

2. Set environment variables

# .env.local
NEXT_PUBLIC_VAPID_PUBLIC_KEY=your-public-key
VAPID_PRIVATE_KEY=your-private-key

3. Wrap your app with NextPushProvider

import { NextPushProvider } from 'next-push/client';

function App() {
  return (
    <NextPushProvider>
      <YourApp />
    </NextPushProvider>
  );
}

4. Use in your component

import { useNextPush } from 'next-push/client';

function MyComponent() {
  const { subscribe, subscribed } = useNextPush();
  
  return (
    <button onClick={subscribe}>
      {subscribed ? 'Unsubscribe' : 'Subscribe'}
    </button>
  );
}

Features

🔔

Easy Integration

Simple React hook for client-side push notifications

🛡️

Type Safety

Full TypeScript support with proper type definitions

Lightweight

Minimal bundle size with no heavy dependencies

🔒

Secure

Built-in VAPID key support for secure push notifications

📱

Cross-Platform

Works across all modern browsers and devices

🎯

Flexible

Customizable notification content and behavior

🔄

Auto-Management

Automatic service worker registration and subscription handling

🏗️

Modular

Separate client and server modules for better tree-shaking

API Reference

useNextPush Hook

A React hook that provides push notification functionality.

const {
  isSupported,    // boolean - Whether push notifications are supported
  subscribed,     // boolean - Current subscription status
  loading,        // boolean - Loading state for async operations
  permission,     // NotificationPermission - Current notification permission
  error,          // PushError | null - Current error state
  subscription,   // PushSubscription | null - Current push subscription object
  subscribe,      // function - Subscribe to push notifications
  unsubscribe,    // function - Unsubscribe from push notifications
  toggle,         // function - Toggle subscription state
  reset           // function - Reset error state and progress
} = useNextPush();

Configuration Options

interface PushConfig {
  vapidPublicKey?: string;        // Optional - automatically loaded from env
  defaultIcon?: string;           // Default icon URL for notifications
  onNotificationClick?: (url?: string) => void;
  logger?: (message: string, type: 'info' | 'error') => void;
  retryAttempts?: number;         // Number of retry attempts (default: 3)
  retryDelay?: number;            // Delay between retries in ms (default: 1000)
  autoSubscribe?: boolean;        // Auto subscribe when permission granted
}

Examples

Basic Usage

import { useNextPush } from 'next-push/client';

export default function Home() {
  const { isSupported, subscribed, subscribe, unsubscribe } = useNextPush();

  return (
    <div>
      {isSupported && (
        <button onClick={subscribed ? unsubscribe : subscribe}>
          {subscribed ? 'Unsubscribe' : 'Subscribe'}
        </button>
      )}
    </div>
  );
}

Error Handling

const { subscribe, error } = useNextPush();

if (error) {
  switch (error.type) {
    case 'PERMISSION_DENIED':
      return <div>Please enable notifications in browser settings</div>;
    case 'VAPID_MISSING':
      return <div>VAPID key not configured</div>;
    case 'NOT_SUPPORTED':
      return <div>Push notifications not supported in this browser</div>;
    default:
      return <div>Error: {error.message}</div>;
  }
}

Server-Side Setup

import { createServerPush } from 'next-push/server';

const pushServer = createServerPush('admin@example.com', {
  publicKey: process.env.VAPID_PUBLIC_KEY!,
  privateKey: process.env.VAPID_PRIVATE_KEY!
});

// Send notification to a single subscription
const result = await pushServer.sendNotification(subscription, {
  title: 'Hello!',
  message: 'This is a test notification',
  url: 'https://example.com',
  icon: '/icon.png'
});

Setup Requirements

1. Generate VAPID Keys

npx web-push generate-vapid-keys

2. Create Service Worker

Create public/sw.js with the provided template.

self.addEventListener('push', (event) => {
  if (!event.data) return;
  
  const data = event.data.json();
  const options = {
    body: data.message,
    icon: data.icon || '/icon.png',
    data: { url: data.url, ...data }
  };

  event.waitUntil(
    self.registration.showNotification(data.title, options)
  );
});

3. Environment Variables

# Client-side (public)
NEXT_PUBLIC_VAPID_PUBLIC_KEY=your-public-key

# Server-side (private)
VAPID_PRIVATE_KEY=your-private-key
Next-Push Logo

by clqu