node.js - Custom Server in Nextjs with socket io and Next API Page Routing - Stack Overflow

Im Trying to do migration and integration from nodejs based socket io server into next js. I have follo

Im Trying to do migration and integration from nodejs based socket io server into next js. I have follow some tutorial based on reference below, but it left me stuck in this error.

 ⨯ TypeError: next__WEBPACK_IMPORTED_MODULE_8___default(...) is not a function
    at eval (server.ts:16:17)
    at <unknown> (rsc)/./server.ts (/Users/netdb/Documents/project/livechat_migration/livechat-fe/build/server/app/api/auth/adduser_and_login/route.js:186:1)
    at __webpack_require__ (build/server/webpack-runtime.js:33:43)
    at addUserAndLogin (app/controllers/authController.js:31:28)
    at POST (app/api/auth/adduser_and_login/route.ts:16:27)
  14 | const hostname = "localhost";
  15 | const port = 3000;
> 16 | const app = next({ dev, hostname, port })
     |                 ^
  17 | const handle = app.getRequestHandler()
  18 | const userSockets: Record<string, any[]> = {};
  19 |

what left me confused is that the error shown as route.ts is actually my server.ts at the root of the project which shown below.

import { Server } from "socket.io";
import http from "http";
import jwt from "jsonwebtoken";
import { decryptData } from "./middlewares/instanceVerification";
import { defineSockets } from "./sockets/socket";
import { connectDatabase } from "./lib/db/db";
import dotenv from "dotenv";
import express, { Request, Response } from "express";
import next from 'next'

dotenv.config();

const dev = process.env.NODE_ENV !== 'production'
const hostname = "localhost";
const port = 3000;
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()
const userSockets: Record<string, any[]> = {};


const serverex = express();

// Initialize HTTP Server
app.prepare().then(() => {
    serverex.all("*", (req: Request, res: Response) => {
      return handle(req, res);
    });
    const server = http.createServer(serverex);
    const io = new Server(server, {
      transports: ["websocket"],
    });
 
    io.on("connection", (socket) => {
    try {
      io.emit("CONNECTED", socket.id);
      const siteName = socket.handshake.query["site-name"];
      const token = socket.handshake.query["token"];
      const instanceToken = socket.handshake.query["instance-token"];
  
      let userId = "";
      jwt.verify(token as string, process.env.ACCESS_TOKEN_SECRET as string, (err, user: any) => {
        if (err) return;
        userId = user.id;
      });
  
      console.log("CONNECTED", userId, socket.id);
      if (!userSockets[userId]) {
        userSockets[userId] = [];
      }
      userSockets[userId].push(socket);
  
      socket.on("disconnect", () => {
        if (userSockets[userId]) {
          userSockets[userId] = userSockets[userId].filter((s) => s !== socket);
          if (userSockets[userId].length === 0) delete userSockets[userId];
        }
        console.log(`Socket ${socket.id} disconnected`);
      });
  
      const { instanceName, instanceId } = decryptData(instanceToken as string, "your_secret_key");
      const instance = `${instanceName}_${instanceId}`;
      defineSockets({ io, socket, userSockets, userId, siteName, instance });
    } catch (error) {
      console.error("WebSocket Error:", error);
    }
    });
    
    // Start the WebSocket Server
    const PORT = process.env.WS_PORT || 3000;
    server.listen(PORT, async () => {
        await connectDatabase();
        console.log(`✅ WebSocket server running on port ${PORT}`);
    });

})

reference 1:

reference 2:

package.json script

  "scripts": {
    "start": "react-scripts start",
    "dev": "npx tsx server.ts",
    "build": "next build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

appreciate any kind of help, if requiring any detail can just comment down below.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744255115a4565359.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信