Implementing Real-time Notifications Using Laravel Websockets and Next.js: A Complete Guide

Real-time notifications are the backbone of modern, interactive web applications. Whether you're building a collaborative dashboard, a messaging app, or a dynamic e-commerce platform, instant feedback and updates significantly boost user engagement. But how do you implement reliable, scalable, and secure real-time notifications using Laravel Websockets and a Next.js frontend?
In this comprehensive guide, you'll learn exactly how to set up, integrate, and optimize a real-time notification system using Laravel Websockets and Next.js. We'll walk through practical steps, real-world tips, and best practices—ensuring your app delivers a seamless user experience.
Why Real-time Notifications Matter
Notifications that reach users instantly—without requiring a page refresh—have become an essential feature for modern web applications. Real-time notifications help:
- Improve responsiveness and user satisfaction
- Enable collaboration and instant feedback
- Keep users informed about important events (messages, orders, system alerts)
Laravel Websockets: The Open Source Pusher Alternative
Laravel Websockets is a powerful open-source package that brings WebSocket server capabilities directly to your Laravel application, allowing you to broadcast events without relying on third-party services like Pusher.
Key benefits of Laravel Websockets:
- Cost-effective: No need for Pusher subscription fees.
- Full control: Host your own socket server, integrate with Laravel broadcasting.
- Flexible: Support for multiple broadcasting drivers and custom authentication.
- Performance: Handles thousands of concurrent connections.
Next.js: The Perfect Frontend for Real-time Apps
Next.js, powered by React, offers fast, server-side rendering and seamless API integration. When paired with Laravel as a backend, it creates a robust, scalable stack for building real-time experiences.
Why use Next.js for real-time notifications?
- SSR/SSG support for fast initial page loads
- React components for dynamic, interactive UIs
- Easy integration with WebSocket libraries and Laravel Echo
- Scalability for both small and large projects
Architecture Overview: Laravel Backend with Next.js Frontend
A typical real-time notification system with these technologies looks like this:
- User action/trigger occurs (e.g., new message, order placed).
- Laravel event is fired and broadcast via Websockets.
- WebSocket server (Laravel Websockets) relays the event.
- Next.js frontend (using Laravel Echo and a WebSocket client) listens for events and updates the UI instantly.
Step-by-Step Laravel Websockets and Next.js Integration Guide
Let's dive into building a real-time notification system using Laravel Websockets and Next.js. We'll cover setup, event broadcasting, frontend integration, and security.
1. Setting Up Laravel Websockets
Start by installing the beyondcode/laravel-websockets package in your Laravel project:
composer require beyondcode/laravel-websockets
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
php artisan migrate
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
Update your .env and config/broadcasting.php to use the pusher driver, but point to your local WebSocket server:
PUSHER_APP_ID=local
PUSHER_APP_KEY=localkey
PUSHER_APP_SECRET=localsecret
PUSHER_APP_CLUSTER=mt1
In config/broadcasting.php:
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => false,
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'http',
],
],
Run your WebSocket server:
php artisan websockets:serve
2. Broadcasting Events from Laravel
Define a notification event in Laravel:
php artisan make:event NewNotification
Edit the event to implement ShouldBroadcast:
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast;class NewNotification implements ShouldBroadcast { public $data;
public function __construct($data) { $this->data = $data; } public function broadcastOn() { return ['notifications']; }
}
Dispatch the event from anywhere in your app:
broadcast(new NewNotification(['message' => 'Hello, world!']));
3. Integrating Laravel Echo with Next.js
Laravel Echo is a JavaScript library that makes subscribing to channels and listening for events effortless.
Install Echo and Pusher JS Client
Next.js uses npm/yarn for frontend dependencies:
npm install laravel-echo pusher-js
Configure Echo in Next.js
Create a utility file (e.g., lib/echo.js):
import Echo from 'laravel-echo'; import Pusher from 'pusher-js';window.Pusher = Pusher;
const echo = new Echo({ broadcaster: 'pusher', key: 'localkey', wsHost: '127.0.0.1', wsPort: 6001, forceTLS: false, disableStats: true, enabledTransports: ['ws', 'wss'], });
export default echo;
Use this echo instance in any React component to listen for notifications:
import { useEffect } from 'react'; import echo from '../lib/echo';
export default function Notifications() { useEffect(() => { const channel = echo.channel('notifications'); channel.listen('NewNotification', (e) => { alert(New notification: ${e.data.message}); }); return () => { channel.stopListening('NewNotification'); }; }, []); return null; }
4. Authenticating Private and Presence Channels
For user-specific notifications, use private channels. Make sure your Laravel backend provides authentication via /broadcasting/auth.
- Set up Laravel Sanctum or Passport for API authentication.
- Configure Echo in Next.js to send authentication tokens (e.g., via headers or cookies).
5. Best Practices for Real-time Notifications
- Use queues for event broadcasting to avoid blocking requests.
- Debounce client notifications to prevent alert fatigue.
- Log and monitor your WebSocket server for dropped connections or errors.
- Secure WebSocket connections with HTTPS in production.
- Scale horizontally by running multiple WebSocket server instances with a shared Redis backend.
Latest News & Trends
Stay ahead with the latest developments in real-time app architecture and tools:
- Adoption of Self-hosted WebSockets: More organizations are migrating from managed services like Pusher to self-hosted solutions for cost control and data sovereignty.
- Next.js 13+ and Server Components: New features in Next.js enhance server-side interactivity, making real-time UI updates more seamless.
- Security Focus: There is increased emphasis on securing WebSocket connections, including JWT-based authentication and WSS-only deployments.
- Hybrid Stacks Gain Popularity: Combining Laravel backends with React/Next.js frontends is now a mainstream approach for scalable, modern web apps.
Common Issues and Troubleshooting
- CORS and WebSocket Origin Errors: Ensure your
websockets.phpconfig and server allow connections from your frontend domain. - Authentication Failures: Double-check token/cookie handling between Next.js and Laravel.
- Production HTTPS Setup: Always use secure WebSockets (
wss://) in production with valid SSL certificates.
Real-world Example: Notification Flow
- User triggers an event (e.g., sends a message).
- Backend broadcasts a notification via Laravel Websockets.
- Next.js client receives the event through Echo and updates the UI instantly.
This architecture works for:
- Chat and messaging systems
- Order and delivery notifications
- Collaborative editing tools
- Activity feeds
Conclusion: Build Engaging, Real-time Web Apps
Implementing real-time notifications with Laravel Websockets and Next.js empowers you to create applications that are interactive, scalable, and enjoyable to use. By following the setup and integration steps above, you'll deliver a seamless, modern user experience—without recurring third-party costs.
Ready to take your real-time app to the next level? Experiment with custom notification channels, presence features, and advanced authentication for even more value.
About Prateeksha Web Design
Prateeksha Web Design specializes in building scalable, real-time web solutions using Laravel and Next.js. We help businesses implement secure, high-performance notification systems and interactive features tailored to your needs.
Chat with us now Contact us today.