Skip to content

React Push Notifications is a modern web application that shows how to implement push notifications using OneSignal. It is built with React 19, TypeScript, and Vite. The app offers a simple interface for managing and testing browser push notifications.

License

Notifications You must be signed in to change notification settings

weezykon/react-push-notifs

Repository files navigation

React Push Notifications

A modern, production-ready web application demonstrating push notification implementation using OneSignal. Built with React 19, TypeScript, and Vite, this project provides a comprehensive example of integrating browser push notifications with real-time subscription management and user-friendly UI.

Table of Contents

Features

Core Functionality

  • OneSignal Integration: Enterprise-grade push notification infrastructure supporting all major browsers
  • Real-time Subscription Management: Track and display push subscription status with live updates
  • Permission Handling: Graceful browser notification permission requests with status feedback
  • Test Notification System: Built-in functionality to send and test notifications locally
  • User Authentication: Simple username-based authentication with localStorage persistence
  • Notification History: View all received notifications with timestamps in a scrollable feed

Technical Features

  • Service Worker Integration: Proper service worker setup for background notifications
  • Foreground Notifications: Handle notifications when the app is active
  • Subscription Diagnostics: Check subscription ID and opt-in status
  • Error Handling: Comprehensive error handling for OneSignal initialization and operations
  • Responsive Design: Modern, mobile-friendly UI with gradient styling
  • TypeScript: Full type safety throughout the application

UI/UX Features

  • Modern Design: Beautiful gradient backgrounds with glassmorphism effects
  • Status Indicators: Visual feedback for notification permissions and subscription state
  • Real-time Updates: Instant notification display without page refresh
  • User-friendly Interface: Clean, intuitive layout with clear action buttons

Tech Stack

Core Technologies

  • React 19.1.1 - Latest React with improved performance and features
  • TypeScript 5.8.3 - Static typing for enhanced developer experience
  • Vite 7.1.7 - Fast build tool with HMR (Hot Module Replacement)

Libraries & Frameworks

  • react-onesignal 3.4.0 - Official OneSignal SDK for React
  • TailwindCSS 3.4.17 - Utility-first CSS framework
  • GSAP 3.13.0 - Professional-grade animation library

Development Tools

  • ESLint 9.36.0 - Code linting with React-specific rules
  • PostCSS 8.5.6 - CSS transformations
  • Autoprefixer 10.4.21 - Automatic vendor prefixing

Prerequisites

Before running this project, ensure you have:

  1. Node.js (v18 or higher) and npm installed
  2. OneSignal Account: Create a free account at OneSignal
  3. OneSignal App ID: Set up a web push app in OneSignal dashboard
  4. Modern Browser: Chrome, Firefox, Safari, or Edge with push notification support

Installation

  1. Clone the repository

    git clone <repository-url>
    cd react-push-notifs
  2. Install dependencies

    npm install
  3. Set up environment variables

    cp .env.example .env
    # Edit .env with your OneSignal App ID

Configuration

Environment Variables

Create a .env file in the root directory:

VITE_ONESIGNAL_APP_ID=your-onesignal-app-id-here

How to get your OneSignal App ID:

  1. Log in to OneSignal Dashboard
  2. Create a new Web Push app or select existing one
  3. Navigate to Settings → Keys & IDs
  4. Copy the "OneSignal App ID"

OneSignal Service Worker Setup

The project includes required OneSignal service worker files in the public/ directory:

  • OneSignalSDKWorker.js - Main service worker
  • OneSignalSDK.sw.js - OneSignal SDK service worker
  • OneSignalSDKUpdaterWorker.js - Update handler

These files are automatically served by Vite and enable background notification support.

Vite Configuration

The vite.config.ts includes special configuration for development:

export default defineConfig({
  plugins: [react()],
  server: {
    allowedHosts: ['.ngrok-free.app', '.ngrok.io'],
  },
})

This allows testing with tunneling services like ngrok for testing push notifications on mobile devices.

Running the Application

Development Mode

npm run dev

The application will start at http://localhost:5173 (or next available port).

Testing with ngrok (for mobile testing)

Push notifications require HTTPS or localhost. To test on mobile devices:

# Start the dev server
npm run dev

# In another terminal, start ngrok
ngrok http 5173

Use the provided ngrok URL to access the app from any device.

Linting

npm run lint

Type Checking

npm run build  # This includes type checking

Project Structure

react-push-notifs/
├── public/
│   ├── OneSignalSDKWorker.js       # Service worker for OneSignal
│   ├── OneSignalSDK.sw.js          # OneSignal SDK service worker
│   ├── OneSignalSDKUpdaterWorker.js # Service worker updater
│   └── vite.svg                     # App icon
├── src/
│   ├── components/
│   │   └── PushNotification.tsx    # Notification component
│   ├── hooks/
│   │   └── useOneSignal.ts         # OneSignal custom hook
│   ├── App.tsx                      # Main application component
│   ├── main.tsx                     # Application entry point
│   └── index.css                    # Global styles
├── .env                             # Environment variables
├── vite.config.ts                   # Vite configuration
├── tailwind.config.js               # TailwindCSS configuration
├── tsconfig.json                    # TypeScript configuration
└── package.json                     # Project dependencies

How It Works

OneSignal Integration Flow

  1. Initialization: On app load, OneSignal SDK initializes with your App ID
  2. Service Worker Registration: Browser registers OneSignal service workers
  3. Permission Request: User clicks "Enable Notifications" button
  4. Subscription: Browser requests permission and creates push subscription
  5. Token Generation: OneSignal generates a unique subscription ID
  6. Notification Delivery:
    • Foreground: Notifications received while app is open
    • Background: Service worker handles notifications when app is closed

Key Components

App.tsx

Main application logic including:

  • OneSignal initialization
  • Subscription state management
  • Notification permission handling
  • User authentication flow
  • UI rendering

Service Workers

The public service worker files handle:

  • Background notification reception
  • Notification click events
  • Push subscription management

State Management

The app uses React hooks for state management:

  • useState for local component state
  • useEffect for OneSignal initialization and lifecycle
  • useRef to prevent duplicate initialization
  • localStorage for username persistence

Usage Guide

For End Users

  1. Access the Application: Open the app in your browser
  2. Enter Username: Provide a username to continue
  3. Enable Notifications: Click "Enable Notifications" and allow browser permission
  4. Check Status: View your subscription status in the sidebar
  5. Test Notifications: Use the test form to send local notifications
  6. View History: All notifications appear in the "Recent Notifications" panel

For Developers

Sending Notifications from Backend

To send notifications from your server, use OneSignal's REST API:

const sendNotification = async (subscriptionId, title, message) => {
  const response = await fetch('https://onesignal.com/api/v1/notifications', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Basic YOUR_REST_API_KEY'
    },
    body: JSON.stringify({
      app_id: 'YOUR_APP_ID',
      include_player_ids: [subscriptionId],
      headings: { en: title },
      contents: { en: message }
    })
  });
  return response.json();
};

Listening to Notification Events

// Foreground notifications
OneSignal.Notifications.addEventListener('foregroundWillDisplay', (event) => {
  console.log('Notification received:', event.notification);
});

// Notification clicks
OneSignal.Notifications.addEventListener('click', (event) => {
  console.log('Notification clicked:', event.notification);
});

Getting Subscription Information

const subscriptionId = OneSignal.User.PushSubscription.id;
const optedIn = OneSignal.User.PushSubscription.optedIn;
const token = OneSignal.User.PushSubscription.token;

Building for Production

Create Production Build

npm run build

This creates an optimized production build in the dist/ directory.

Preview Production Build

npm run preview

Production Considerations

  1. HTTPS Required: Push notifications only work on HTTPS domains (except localhost)
  2. Service Worker Scope: Ensure service workers are served from root domain
  3. Environment Variables: Set production OneSignal App ID
  4. CSP Headers: Configure Content Security Policy if needed
  5. Browser Compatibility: Test on all target browsers

Deployment

Recommended Platforms

  • Vercel: Zero-config deployment for Vite apps
  • Netlify: Simple continuous deployment
  • AWS Amplify: Full-stack deployment
  • Firebase Hosting: Google's hosting solution

Deployment Steps (Vercel Example)

# Install Vercel CLI
npm i -g vercel

# Deploy
vercel

Environment Variables in Production

Set VITE_ONESIGNAL_APP_ID in your hosting platform's environment variable settings.

Troubleshooting

Common Issues

1. Notifications not working

  • Verify HTTPS or localhost usage
  • Check browser notification permissions
  • Ensure OneSignal App ID is correct
  • Check browser console for errors

2. Service Worker errors

  • Clear browser cache and service workers
  • Ensure service worker files are in public/ directory
  • Check network tab for 404 errors on worker files

3. Subscription not creating

  • Wait a moment after permission grant
  • Check OneSignal dashboard for subscription
  • Verify browser supports push notifications
  • Try in incognito mode to rule out extension conflicts

4. Permission already denied

  • Guide users to browser settings
  • Instructions vary by browser (Chrome: Site Settings → Notifications)

5. Build errors

  • Clear node_modules and reinstall: rm -rf node_modules && npm install
  • Check Node.js version compatibility
  • Run npm run lint to check for code issues

Debug Mode

Check browser console for OneSignal debug logs. Enable verbose logging:

OneSignal.Debug.setLogLevel('trace');

Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Code Standards

  • Follow TypeScript best practices
  • Use ESLint configuration provided
  • Write meaningful commit messages
  • Test on multiple browsers before submitting

License

This project is open source and available under the MIT License.

Resources

Support

For issues and questions:


Built with by [Your Name] | Powered by OneSignal

About

React Push Notifications is a modern web application that shows how to implement push notifications using OneSignal. It is built with React 19, TypeScript, and Vite. The app offers a simple interface for managing and testing browser push notifications.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published