Using Relay with Next.js

Connect your Next.js app to a Relay WebSocket server using the Pusher JS client.

Skip the server setup. Relay Cloud gives you managed WebSockets with a free tier. Connect in 60 seconds. Try free →

Prerequisites

  • A running Relay server
  • Your App Key and Host
1

Install

npm install pusher-js
2

Create lib/relay.ts

import Pusher from 'pusher-js';

const relay = new Pusher(process.env.NEXT_PUBLIC_RELAY_APP_KEY!, {
  wsHost: process.env.NEXT_PUBLIC_RELAY_HOST ?? 'ws.relaycloud.dev',
  wsPort: Number(process.env.NEXT_PUBLIC_RELAY_PORT ?? 443),
  wssPort: Number(process.env.NEXT_PUBLIC_RELAY_PORT ?? 443),
  forceTLS: true,
  disableStats: true,
  enabledTransports: ['ws', 'wss'],
  cluster: 'relay',
});

export default relay;
3

Environment Variables

Add these to your .env.local file:

NEXT_PUBLIC_RELAY_APP_KEY=your-app-key
NEXT_PUBLIC_RELAY_HOST=ws.relaycloud.dev
NEXT_PUBLIC_RELAY_PORT=443
4

Subscribe in a Component

'use client';

import { useEffect, useState } from 'react';
import relay from '@/lib/relay';

export default function LiveFeed() {
  const [messages, setMessages] = useState<string[]>([]);

  useEffect(() => {
    const channel = relay.subscribe('public-feed');

    channel.bind('message.sent', (data: { message: string }) => {
      setMessages(prev => [...prev, data.message]);
    });

    return () => {
      relay.unsubscribe('public-feed');
    };
  }, []);

  return (
    <ul>
      {messages.map((msg, i) => <li key={i}>{msg}</li>)}
    </ul>
  );
}
5

Private Channels

To subscribe to private channels, your Next.js app needs an auth endpoint that validates the user and returns a signed token. Configure the authEndpoint option on the Pusher client to point to your backend route. See the API reference for full details on the authentication flow.

Relay is fully Pusher-protocol compatible. Any Pusher JS tutorial applies directly — just swap the host and disable stats.

Ready to skip the server setup? Relay Cloud gives you a production WebSocket server instantly. Start free, upgrade when you grow. Start free →