Created
October 26, 2021 13:53
-
-
Save steveruizok/5d5d695854ba0627c695ac5f8df05247 to your computer and use it in GitHub Desktop.
Pusher auth for a Next.js app.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pages/pusher/pusher-auth.ts | |
import { pusher } from "backend/pusher" | |
import { NextApiHandler, NextApiRequest } from "next" | |
interface PushAuthRequest extends NextApiRequest { | |
body: { | |
socket_id: string | |
channel_name: string | |
} | |
} | |
const PushAuthHandler: NextApiHandler = (req: PushAuthRequest, res) => { | |
const { socket_id, channel_name } = req.body | |
res.send( | |
pusher.authenticate(socket_id, channel_name, { | |
user_id: id, | |
user_info: { | |
// ...presence info here | |
}, | |
}) | |
) | |
} | |
export default PushAuthHandler |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// backend/pusher.ts | |
export const pusher = new Pusher({ | |
appId: process.env.NEXT_PUBLIC_PUSHER_APP_ID, | |
key: process.env.NEXT_PUBLIC_PUSHER_KEY, | |
secret: process.env.NEXT_PUBLIC_PUSHER_SECRET, | |
cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER, | |
useTLS: true, | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hooks/usePusher.ts | |
import Pusher, { Channel } from "pusher-js" | |
function usePusher(roomId: string) { | |
React.useEffect(() => { | |
const channel = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY, { | |
cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER, | |
authEndpoint: "/api/pusher-auth", | |
}) | |
.subscribe("presence-" + roomId) | |
return () => { | |
channel.disconnect() | |
}, [roomId]) | |
return channel | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment