Estoy tratando de usar Pusher en mi aplicación Next.js porque vercel no permite websockets en sus funciones sin servidor. Sigo recibiendo este error después de ejecutar el programa con Pusher. error - unhandledRejection: PusherRequestError: Unexpected status code 400
Hice mi código lo más básico posible para tratar de obtener ayuda con él. Solo estoy usando el ejemplo de doc básicamente:
Aquí está mi código de back-end en la función sin servidor Next.js:
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(); }Llamar a esta función en mi código de cliente:
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;Puede deberse a que está intentando acceder a las variables env desde el cliente, NextJS no las expone al navegador. Puedes poner NEXT_PUBLIC_ como prefijo para hacerlo público;
Referencia: https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser .