Next.js Discord

Discord Forum

Socket.io - High Frequency of Requests

Unanswered
Japanese flying squid posted this in #help-forum
Open in Discord
Avatar
Japanese flying squidOP
I've custom server.js with socket.io. It was working normally, but I think I god DDoS attack. I've changed server from render to VPS hostinger. Also added cloudflare. I made website work and stay alive but I can't help socket.io. I am getting thousands of requests on socket.io every minute. It doesn't stop.

I get this error: GET https://www.kisa.ge/socket.io?EIO=4&transport=polling&t=PGv5Sxa net::ERR_TOO_MANY_REDIRECTS
Status Code: 308 Permanent Redirect
Image
Image

148 Replies

first, if u have a vps and nginx, use certbot
then, u dont need a seperate socket.io handler in your nginx config
also, setting up a seperate api with express on a different port for socket.io is highly recommended
Avatar
@gin also, setting up a seperate api with express on a different port for socket.io is highly recommended
Avatar
Japanese flying squidOP
Can you help me to do all this stuff?
I am using Certbot already
Avatar
@Japanese flying squid did you exposed your ports correctly, so your server can handle that request (should be ufw on ubuntu)?
Also, where did you got these logs from?
Avatar
Japanese flying squidOP
I got logs from: sudo tail -f /var/log/nginx/access.log
And PORT is the same, I am using sockets from same next.js custom server, 3000 PORT
I didn’t expose anything manually from VPS
Avatar
@Japanese flying squid ah ok. Try to search on how to setup a socket connection via your VPS. Then check against what you have done and change it
Avatar
Japanese flying squidOP
I couldn't find anything helpful online 😦
@B33fb0n3
Avatar
@Japanese flying squid I am using Certbot already
Avatar
but your setup is false
Avatar
@Japanese flying squid I couldn't find anything helpful online 😦
Avatar
this might help you: https://www.youtube.com/results?search_query=connect+socket.io+with+VPS+server

When you hosting though docker, then you should also set up nginx. The first video (this one: https://www.youtube.com/watch?v=uVTSBsUmB7A) for example clarifies how you need to change your nginx config to be able to use socket.io
Avatar
@gin but your setup is false
Avatar
what is his setup?
Avatar
i already told him what he has to do
having a custom server with nextjs is very bad
u loose a bunch of critical features
Avatar
@B33fb0n3 what is his setup?
Avatar
he is proxying the same port twice
Avatar
@gin u loose a bunch of critical features
Avatar
what's for example? When self hosting it, all nextjs features are supported
Avatar
Japanese flying squidOP
@gin can you help me with setting up different socket.io server on VPS? I've not a lot of experience with VPS
Image
also u dont need extra setup for sockets
cause nginx supports it by native
make sure if u use cloudflare to enable wss support
cause sometimes it may be disabled
so socketio will switch to polling which will extremely increase the requests
yeah btw
Avatar
Japanese flying squidOP
so I've to set upanother socket server with express, run it for examplelocalhost:3001, and connect from Next.js app to localhost:3001 socket server?
Avatar
i see in your screenshot
@Japanese flying squid can u go inside your networks tab and send me a screenshot of the first init connection socketio makes?
filter by websocket
Avatar
@gin u mean custom server?
Avatar
the Automatic Static Optimization link, links to the pages router. And also all the content itself is about the pages router. So it isn't relevant for the app router

Read more: https://nextjs.org/docs/app/building-your-application/configuring/custom-server
Avatar
Japanese flying squidOP
@gin Inside networks, when I filter WS I don;t get any messages
Avatar
Japanese flying squidOP
Image
Avatar
yeah
okay next step, create a custom server for socket.io
and run it on a different port
Avatar
its just that if u switch for websockets to a serverfull extern server u will have less problems
Avatar
Japanese flying squidOP
I've nto yet done cloudflare
this my nginx config rn
Image
Avatar
@Japanese flying squid make sure you also set this, because of the SSL certificate:
Image
Avatar
Japanese flying squidOP
Yes, it's Full encryption rn
Avatar
@Japanese flying squid this my nginx config rn
Avatar
ignore that config
Avatar
Japanese flying squidOP
Image
Avatar
its faulty rn thats why u getting a 308
Avatar
Japanese flying squidOP
Image
@gin I will go and set up new repository for express websockets server, correct?
Avatar
yes
and remove custom server from nextjs
the rest is self explanatory, if u want to use the same endpoint, u can just route a path to a different port in nginx
so everything under yourdomain.com/socket routes to localhost:3001 (your socketio backend)
or u create a subdomain like socket.yourdomain.com, makes the setup easier
this is the only thing to consider when u have a external server, u will profit a lot having a seperate backend
talking from experience
Avatar
Japanese flying squidOP
I need to make it asap for now
Image
Is it okay?
Avatar
yes
Avatar
Japanese flying squidOP
Image
Now just delete server.js from next?
Avatar
yes
and just run your app like normal
next start, dev and else
Avatar
Japanese flying squidOP
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "node .next/standalone/server.js",
"prod_start": "NODE_ENV=production node server.js",
"lint": "next lint",
"deploy": "npm run build && git add . && git commit -m 'deploy' && git push"
},
Avatar
your prod_start to next start
dont need node env since start is in production mode
Avatar
Japanese flying squidOP
from my dockerfile I started server like
# Start the server
CMD ["node", "server.js"]
so I should change it "npm" "start"?
Avatar
yes
Avatar
Japanese flying squidOP
and insit start script leave : "start": "node .next/standalone/server.js",?
or change to next start
i just remembered on standalone u dont need next start cause it bundles everything
Avatar
Japanese flying squidOP
"use client";

import { io } from "socket.io-client";

export const socket = io();


what about this?
this is my socket.ts
and then using like this

import { socket } from "./socket";
import { T_SocketEvent } from "./socket.types";

const socketEmit = (event: T_SocketEvent, data: any) => {
socket.emit(event, data);
};

export default socketEmit;
Avatar
@Japanese flying squid "use client"; import { io } from "socket.io-client"; export const socket = io(); what about this?
Avatar
this a hook i usually use for my apps
import {io} from "socket.io-client";

let socket: ReturnType<typeof io>;

export default function useSocket() {
  if (!socket) {
    socket = io("https://yourdomain.com", {
      path: "/api/socket.io",
    });
  }

  return socket;
}
the important thing is to specify the path
just resuse the same socket instance
so u can just refernce it across your app and u will have the same connection
without creating it everytime
Avatar
Japanese flying squidOP
"use client";

import { io } from "socket.io-client";

export const socket = io("http://localhost:3077");
is it okay?
to leave like this?
Avatar
u can leave it like this yes
just define the path
u will probably have it routed to /socket/socket.io
/socket/ routes to your 3077 and, /scoket.io is created internally
on local u can just have it to localhost:3077/socket.io
Avatar
Japanese flying squidOP
wait wait Iam confused now
Avatar
keep what u have
it will work
socket.io-client will use /socketi.io automatically
but on production u need point the path otherwise it will fail
Avatar
Japanese flying squidOP
Image
So I guess it is now okay for localhost
Avatar
👍
Avatar
Japanese flying squidOP
Now I need to build and run my next app to test it, correct?
Avatar
yes :pausechamp:
:shrug:
Avatar
Japanese flying squidOP
You are helping me so much thanks, I need to fix it on prod in like 2 hours maximum
Image
Image
Image
Avatar
what did u run?
Avatar
Japanese flying squidOP
npm run build
npm start - it runs node .next/standalone/server.js
just removing standalone
I will try without standalone
Avatar
delete .next
and try again
its probably because it bundled server.js and didnt delete it
Avatar
Japanese flying squidOP
Better to leave still standalone?
Okay deleted .next and trying again with standalone
Will it be easy to make it work on VPS?
Avatar
standalone is good if use nextjs with docker
Avatar
Japanese flying squidOP
Yes I use
Same problem with new build
Image
Avatar
strange
can i look at the codebase?
Avatar
Japanese flying squidOP
Image
on dev server it's ok
Image
inside .next I don't even see standalone folder
Image
Avatar
how does your next config look like
Avatar
Japanese flying squidOP
Image
Avatar
@Japanese flying squid Click to see attachment
Avatar
do this
cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/
Image
Avatar
Japanese flying squidOP
Image
Image
because inside standalone there is no server.js file
Avatar
just run next start
the standalone folder has its own .next its probably in there
next start will work even with standalone
just do that locally
Avatar
Japanese flying squidOP
Image
Image
but it works now
const io = new Server(httpServer, {
  cors: {
    origin: "http://localhost:3000", // Replace with your client origin
    methods: ["GET", "POST"], // Allowed HTTP methods
    credentials: true, // Allow cookies if needed
  },
});
Should I add my prod url here also inside origin?
Avatar
Japanese flying squidOP
After removing custom server, on prod VPS I get error:

> kisa@1.1.0 start
> next start

sh: next: not found