I encountered an issue while trying to integrate Pusher into my Next.js application due to Vercel's restriction on websockets in their serverless functions. The error message I keep receiving after running the program with Pusher is:
error - unhandledRejection: PusherRequestError: Unexpected status code 400
To simplify matters and seek assistance, I have stripped down my code to its basic form. Essentially, I am following the documentation example:
This is the backend code within the Next.js serverless function:
import Channels from "pusher";
export default async function handler(req, res) {
const channels = new Channels({
app_id: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
});
const data = req.body;
channels && channels.trigger("my-channel", "my-event", data);
res.end();
}
Here is how I call this function in my client-side code:
import Pusher from "pusher-js";
import { useEffect } from "react";
const TryPusher = () => {
useEffect(() => {
setPusherListener();
}, []);
const setPusherListener = () => {
let channels = new Pusher(process.env.PUSHER_APP_KEY, {
cluster: process.env.PUSHER_APP_CLUSTER,
});
let channel = channels.subscribe("my-channel");
channel.bind("my-event", (data) => {
console.log(data)
});
};
const pushData = async (data) => {
// /api/socket is the endpoint for my pusher function
const res = await fetch("/api/socket", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!res.ok) {
console.error("failed to push data");
}
}
return (
<button onClick={async () => await pushData({foo: bar>)}>
Get Data
</button>
);
};
export default TryPusher;