DEV Community

prateekshaweb
prateekshaweb

Posted on • Originally published at prateeksha.com

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

Why this matters (and what you'll get)

Real-time notifications keep apps feeling alive — chat messages, order updates, and collaborative edits should appear without a page refresh. If you want control (and lower recurring costs) compared to hosted services like Pusher, pairing Laravel Websockets with a Next.js frontend is a reliable stack that scales well and is easy to reason about.

This guide gives a practical path: architecture, key steps to implement, common pitfalls, and production best practices so you can ship real-time notifications quickly.

High-level architecture

The flow is simple and predictable:

  1. A user action triggers a server-side event (new message, order placed).
  2. Laravel fires a broadcastable event.
  3. The laravel-websockets server relays the event.
  4. Next.js (via Laravel Echo + Pusher client) listens and updates the UI instantly.

You host the WebSocket server inside your Laravel app (beyondcode/laravel-websockets), and Next.js handles the client-side subscription. This keeps data inside your infrastructure and avoids per-connection charges.

Quick implementation plan

Follow these steps to get a working prototype:

  • Install laravel-websockets and publish migrations/config.
  • Configure broadcasting to use pusher driver but point to your local WebSocket server (host 127.0.0.1, port 6001).
  • Create a broadcastable event in Laravel that implements ShouldBroadcast and dispatch it where needed.
  • In Next.js install laravel-echo and pusher-js, create a shared Echo instance, and subscribe to channels in React components.

Implementation tips:

  • In Laravel, set PUSHER_APP_KEY/SECRET/ID in .env to dummy values and map broadcasting options to your websocket host/port.
  • In Next.js, create a lib/echo.js that configures Echo with wsHost, wsPort, forceTLS false, and enabledTransports ['ws','wss'].
  • Use private channels for user-specific notifications and make sure your /broadcasting/auth endpoint accepts the same auth method as your frontend (cookies or Authorization header).

Practical examples (what to wire up)

You don’t need a long list of commands here — focus on the pieces to wire together:

  • Server-side: make an event, implement ShouldBroadcast, define broadcastOn() channel, and broadcast(new YourEvent($payload)).
  • Client-side: create an Echo instance, call echo.channel('notifications').listen('YourEvent', callback), and tear down the listener in useEffect cleanup.

Small note: If you use Next.js SSR, only instantiate Echo on the client to avoid window references on the server.

Authentication and security

Private and presence channels need authentication. Common approaches:

  • Use Laravel Sanctum for SPA cookie-based auth — Echo can use cookies automatically when running in the browser. This is usually simplest if your Next.js app is served from the same top-level domain or you handle cross-site cookies correctly.
  • If you use token auth (JWT, Passport), configure Echo to send the Authorization header with the bearer token on auth requests.

Never expose an unauthenticated WebSocket endpoint for private channels. In production, switch to wss:// and ensure your SSL certificate is valid.

Best practices and performance tips

Real-time features can be powerful, but easy to get wrong. Follow these recommendations:

  • Queue event broadcasting so web requests don’t block while serializing and sending notifications.
  • Debounce or batch notifications client-side to prevent alert fatigue for frequent events.
  • Monitor the websockets dashboard (laravel-websockets provides one) to track connections and failed broadcasts.
  • Use Redis as a centralized pub/sub backend when running multiple websocket server instances.
  • Provide a fallback (polling or SSE) for environments that block WebSockets.

Troubleshooting checklist

If a notification won’t arrive, check these fast:

  • Is the broadcasting driver set to pusher in config/broadcasting.php?
  • Is the websockets server running (php artisan websockets:serve) and reachable from the frontend host?
  • Are CORS/origin settings allowing connections from your Next.js domain?
  • For private channels, is /broadcasting/auth returning 200 and authorized for the user?

Where to read more and real-world help

If you want a step-by-step walkthrough or a case study, see the article I drew from at https://prateeksha.com/blog/implementing-real-time-notifications-laravel-websockets-nextjs. For company and services, visit https://prateeksha.com and explore more posts at https://prateeksha.com/blog.

Conclusion

Using Laravel Websockets with Next.js gives you control, lowers long-term costs, and keeps latency low for users. Start with a small prototype: a single broadcast event and a Next.js component that listens for it. Once that works, harden auth, move broadcasts to queues, add monitoring, and scale with Redis and additional socket instances.

Real-time is not magic — it's a few well-connected pieces. Wire them carefully, secure them, and your notifications will feel fast, reliable, and delightful.

Top comments (0)