Skip to content

Instantly share code, notes, and snippets.

@alex-cory
Last active August 5, 2023 21:03
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alex-cory/84451eba3257953ca5ccd979c00f9962 to your computer and use it in GitHub Desktop.
Save alex-cory/84451eba3257953ca5ccd979c00f9962 to your computer and use it in GitHub Desktop.
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 }) => (
<PusherProvider {...config}>
<Component {...pageProps} />
</PusherProvider>
)
// 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 => <div>msg.content</div>)
}
// 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()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment