Skip to main content
npayload is launching soon.
npayloadDocs
Framework Quickstarts

React quickstart

Add real-time npayload messaging to a React application

Add real-time messaging to a React application using @npayload/react hooks for subscribing to messages and @npayload/browser for client-side publishing.

Client-side publishing uses a publishable key with limited permissions. For server-side publishing with full access, use @npayload/node in your backend. See the Node.js quickstart.

Prerequisites

  • React 18+
  • A React project (Vite, Create React App, or similar)
  • An npayload account with a publishable key (get one here)

Install the SDKs

npm install @npayload/react @npayload/browser

Add your publishable key to .env:

VITE_NPAYLOAD_KEY=pk_live_your_publishable_key

Add the provider

Wrap your application with NPayloadProvider at the root level.

// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { NPayloadProvider } from '@npayload/react';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <NPayloadProvider
      config={{
        publishableKey: import.meta.env.VITE_NPAYLOAD_KEY,
      }}
    >
      <App />
    </NPayloadProvider>
  </React.StrictMode>
);

Subscribe to messages

Use the useMessages hook to receive real-time messages from a channel.

// src/components/MessageFeed.tsx
import { useMessages } from '@npayload/react';

export function MessageFeed() {
  const { messages, isLoading, error } = useMessages('notifications');

  if (error) {
    return <p>Error: {error.message}</p>;
  }

  if (isLoading) {
    return <p>Connecting...</p>;
  }

  return (
    <ul>
      {messages.map((msg) => (
        <li key={msg.gid}>
          <strong>{msg.payload.event}</strong>: {msg.payload.message}
          <time>{new Date(msg.createdAt).toLocaleTimeString()}</time>
        </li>
      ))}
    </ul>
  );
}

Publish messages

Use the usePublish hook to send messages from the client.

// src/components/PublishForm.tsx
import { useState } from 'react';
import { usePublish } from '@npayload/react';

export function PublishForm() {
  const [text, setText] = useState('');
  const { publish, isPublishing } = usePublish('notifications');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    await publish({
      event: 'message.sent',
      message: text,
      sentAt: new Date().toISOString(),
    });

    setText('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type a message"
        required
      />
      <button type="submit" disabled={isPublishing}>
        {isPublishing ? 'Sending...' : 'Send'}
      </button>
    </form>
  );
}

Put it together

// src/App.tsx
import { MessageFeed } from './components/MessageFeed';
import { PublishForm } from './components/PublishForm';

export default function App() {
  return (
    <div>
      <h1>npayload + React</h1>
      <PublishForm />
      <h2>Messages</h2>
      <MessageFeed />
    </div>
  );
}

Run it

npm run dev

Open http://localhost:5173, type a message, and click Send. The message will appear in the feed in real time.

Next steps

Was this page helpful?

On this page