how to fix "WebSocket connection to 'wss://apiURL/socket.io/?EIO=4&transport=websocket' failed: " - node.js

socket.io works fine on the localhost server, but after deploying it over https, I keep getting this error.
Client code:
export const socket = io.connect(process.env.REACT_APP_SERVER_URL, {
transports: ["websocket"],
// withCredentials: true,
cors: {
origin: [process.env.REACT_APP_SERVER_URL],
// origin: "*",
credentials: true,
},
});
Backend code:
const io = socketIO(server, {
cors: {
origin: [process.env.CLIENT_URL],
// origin: "*",
credentials: true,
},
});
When I type in the console.log "process.env.REACT_APP_SERVER_URL", the server API deployed by https comes in well, but I don't know what's wrong with socket communication.
As mentioned in the socket.io document, I tried using [credentials: true, withCredentials: true], and tried the same method as [origin: "*"] from Google, but all the same errors are coming out.
How can I solve it..?
Any help would be appreciated!

Related

Why Axios request to a node(Express) back-end api still preflight OPTIONS request even if http-proxy-middleware is configured?

I'm trying to figure out why when I make a call to my "API" (nodejs express) from my React client the OPTIONS, preflight request is executed first.
Server api run on http://localhost:8000
Client run on http://localhost:3000
In my React client I configured http-proxy-middleware as follows:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
Also the Axios instance is created with following options
const options = {
baseURL: BASE_URL,
timeout: 300000,
withCredentials: false,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
};
axios.create(config);
The Node.js(Express) BackEnd application is configured as follow:
app.use(cors(
{
"origin": "*", // just for test...
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"allowedHeaders": "*" // just for test
}
));
When I make a Post for instance for server-side token validation a preflight OPTIONS request is made. How can I avoid this ? Am I doing something wrong?
Thank you all.

Problem setting a cookie in a react app in production

I'm having issues setting a cookie in a react app, In development, it works but when I switch to production the cookie is not received by the browser. I'm using a node.js/express server.
The backend and frontend are both hosted on vercel.
This is the list of things I've tried:
I've set the domain name to be the domain of the frontend(i.e ".vercel.app"),
In the request to the backend using axios, "withCredentials" is set to true
Secure is set to true
cors is enabled
Here's the code for clarification:
The code sending the cookie:
function sendCookie(req, res, token) {
const cookies = new Cookies(req, res, {
keys,
});
return cookies.set("jwt", token, {
domain:".vercel.app"
secure: true,
sameSite:"strict"
path: "/",
httpOnly: false,
});
}
Cors configuration:
app.use(
cors({
credentials: true,
origin: [
"http://localhost:5173",
"https://abc.vercel.app",
],
methods: ["GET", "POST", "DELETE", "PATCH"],
})
);
"https://abc.vercel.app" in this case is the frontend URL
I'd really appreciate any help I can get. Thanks

How to deploy in render.com this kind of codebase?

I got this error ::
GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=OLJa9mm net::ERR_CONNECTION_REFUSED
Everything is good but the socket is not working...!!!
const io = require("socket.io")(server, {
pingTimeout: 60000,
cors: {
origin: "http://localhost:3000",
// credentials: true,
},
});
If you do that your problem will fix:
socket.current = io('http://localhost:5000/%27') => socket.current = io('YOURBACKENDURL')

CORS error with socket-io connections on Chrome v88+ and Nestjs server

I have an application connecting to a Nestjs server to establish a WS connection (server is on a different URL, so it is a CORS request).
The WebsocketGateway is defined as such.
#WebSocketGateway(port, {
handlePreflightRequest: (req, res) => {
const headers = {
'Access-Control-Allow-Headers': 'Authorization',
'Access-Control-Allow-Origin': 'the page origin',
'Access-Control-Allow-Credentials': true,
};
res.writeHead(200, headers);
res.end();
}
})
Works like a charm on Chrome v87 and down and on Firefox. Since upgrading my browser to Chrome 88, the front-end socket-io connection goes on a connect-reconnect loop, as:
The preflight request passes and gets a 200 response, with the headers set above;
The actual connection fails with CORS error as the only message in the browser console
Just incase someone else needs this, in your decorator there is a cors property
#WebSocketGateway({ cors: true })
This is how i fixed
import { IoAdapter } from '#nestjs/platform-socket.io';
import { ServerOptions } from 'socket.io';
export class SocketAdapter extends IoAdapter {
createIOServer(
port: number,
options?: ServerOptions & {
namespace?: string;
server?: any;
},
) {
const server = super.createIOServer(port, { ...options, cors: true });
return server;
}
}
main.ts
const app = await NestFactory.create(AppModule, { cors: true });
app.useWebSocketAdapter(new SocketAdapter(app));

ReactJs calling NodeJs api failed with error- 'keycloak-token' of undefined?

I have nodejs api integrated with Keycloak and here is the keycloak configuration
{
"realm": "realm",
"auth-server-url": "<IP-ADDRESS>/auth/",
"ssl-required": "external",
"resource": "client-id",
"verify-token-audience": true,
"public-client": true,
"use-resource-role-mappings": true,
"confidential-port": 0,
"policy-enforcer": {}
}
and here how secure it
//Secure api with Keycloak
const keycloak = require('./config/keycloak-config.js').initKeycloak();
app.use(keycloak.middleware());
app.use("/api/posts",keycloak.protect(), posts);
Now tested with it POSTMAN and in header passed 'Authorization: Bearer Token' and its working totally fine.
Now come to the issue when trying to access same api with reactjs its failing
function getAll(pageNo, limit){
return httpClient({
url: `api/posts?page=${pageNo}&limit=${limit}`,
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer ' +sessionStorage.getItem('authentication'),
'Access-Control-Allow-Origin': '*'
},
});
}
Its failed with the below error
TypeError: Cannot read property 'keycloak-token' of undefined
This issue i was getting because nodejs cors was added after keycloak intialization
const keycloak = require('./config/keycloak-config.js').initKeycloak();
app.use(keycloak.middleware());
app.use(cors({ origin: true }));
Which should be
app.use(cors({ origin: true }));
const keycloak = require('./config/keycloak-config.js').initKeycloak();
app.use(keycloak.middleware());
This issue I was getting because nodejs cors was added after keycloak initialization,
app.use(keycloak.middleware()) after
app.use(cors())

Resources