Encountering an Error when Integrating Pusher (real-time data library) with Next.js: PusherRequestError - Unexpected status code 400

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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while creating a token in a JavaScript Chrome extension and attempting to validate it on a backend Node.js server

Trying to create a token within a chrome extension and utilizing it to authenticate requests to the backend server has proven challenging. While successfully generating a token on the front end, encountering an error when verifying it with the google-auth- ...

The function is returning an undefined value in node.js due to the boolean condition

I have two functions. The first one is in auth.js, and it looks like this: const adminCheck = (req, res) => { console.log(“one”) UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => { if(response) { return true ...

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...

modify the state within a redux reducer

Currently, I am working on a Next.js project that involves Redux and has reducers. In one of the reducers, I am trying to update the initial state after sending a new "task" to the server so that the user can see the new item immediately. However, whenever ...

Utilizing AJAX and jQuery to dynamically load a div instantly, followed by automatic refreshing at set intervals

I am utilizing jQuery and AJAX to refresh a few divs every X seconds. I am interested in finding out how to load these divs immediately upon the page loading for the first time, and then waiting (for example, 30 seconds) before each subsequent refresh. I h ...

Having trouble setting up websocket connection - Using React js with Node Express and Nginx

Need assistance, Encountering the following error in production WebSocket connection to 'wss://subdomain.example.com/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 404 Here is t ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

Obtaining status codes from URLs can be achieved by leveraging various methods

Hey there, I'm just starting out with javascript and AngularJS. Here's a function I wrote to retrieve JSON data from the server: function getProducts() { return $http.get(urlProducts).then( //Success function(resp ...

Steps for retrieving a table of records with Jquery and sending it to the server through AJAX

Displayed below is a table I have: <table cellspacing="0" rules="all" border="1" id="ContentPlaceHolder1_GridView1" style="border-collapse:collapse;" class="table table-striped"> <tbody> <tr> <th scope="col"> ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

Playwright Vercel Error: Unable to launch browserType. The executable cannot be found at the specified directory

After testing my application on various local environments such as Windows, Linux, and macOS where it worked perfectly fine, I encountered an error when deploying my nextjs app on Vercel. browserType.launch: Executable doesn't exist at /home/sbx_user1 ...

Using the Context API dispatch (consumer) within the _app.js class component in Next.js

How can I access the dispatch Context API methods in the _app.js file? The issue I am facing is that I am using React hooks along with Context API, and as _app.js is a Class component, I cannot directly use hooks within it. Below is my current code snipp ...

Guide to developing JavaScript code that moves information from one local website to a different one

Here's the scenario: You input text into a field on website A and click a button. Upon clicking that button, the entered text should appear in website B. I attempted to use localStorage for this functionality, but unfortunately it was not successful. ...

Is there a simpler method for making multiple posts using an AJAX JS loop?

My form is quite extensive and uses AJAX to save. The JavaScript functions are stored in an external file and structured like this: function milestone09() { $.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone09').serialize( ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

Node.js, sigma.js, and the typescript environment do not have a defined window

When attempting to set up a sigma.js project with node.js in TypeScript, I encountered a reference error after starting the node.js server: ts-node index.ts The problem seems to be located within the sigma\utils\index.js file. <nodejsproject& ...

The Angular error TS2531 occurs when attempting to call scrollIntoView on an object that may be null

In my current Angular project, I am attempting to implement a scroll view using ViewChild by id. This is the method I have written: ngOnInit() { setTimeout(() => { if (this.router.url.includes('contact')) { ...

Choose all elements by their class except for a particular container defined by the parent element's ID

Can you provide an example of translating the function below into utilizing the .not method (or not selector)? $(".CLASS").filter(function(i, e){ return (e.parentNode.id != "ID"); } ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...