import { PusherProvider } from '@harelpls/use-pusher' // _app.js const config = { clientKey: 'your-pusher-client-key', cluster: 'us2', // required for private/presence channels authEndpoint: '/api/pusher/auth' } const App = ({ Component, pageProps }) => ( ) // messages.js const Messages = ({ chatId }) => { const [messages, setMessages] = useState([]) const channel = useChannel(`private-${chatId}`) // when a new message is created, add it to the list realtime useEvent(channel, 'message:created', message => { if (message) setMessages(msgs => [...msgs, message]) }) return messages.map(msg =>
msg.content
) } // api/pusher/auth.js /** * Used to authenticate pusher */ import Pusher from 'pusher' const pusher = new Pusher({ appId: '1234567', key: 'sdgw3434ggsd2342d', secret: process.env.PUSHER_SECRET, cluster: 'us2', encrypted: true }) export default async(req, res) => { try { const socketId = req.body.socket_id // aka private-chatId const channel = req.body.channel_name const { db } = await connect() const chatId = channel.split('-')[1] const result = await db.collection('chats').find({ _id: ObjectId(chatId) }) const chat = await result.next() if (chat._id.toString()) { const auth = pusher.authenticate(socketId, channel) return res.send(auth) } } catch (err) { console.log('Pusher Auth Error: ', err) res.status(403).end() } }