I am trying to use Pusher in my Next.js application because vercel doesn't allow websockets in their serverless functions. I keep getting this error after running the program with Pusher. error - unhandledRejection: PusherRequestError: Unexpected status code 400
I made my code as basic as possible to try and get help with it. I'm just using the doc example basically:
Here is my back-end code in 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();
}
Calling this function in my client-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;
It might be because you are trying to access env variables from client, NextJS does not expose these to the browser. You can put NEXT_PUBLIC_ as a prefix to make it public;
Reference: https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser.