I have configured a Signal R connection in my next.js component.
import { useState } from 'react';
import { HubConnectionBuilder } from '@microsoft/signalr';
import { useGlobalState } from '@/context/GlobalStateContext';
interface ConfigProps {
config: Config
}
export interface Config {
connect: boolean
}
const SignalRComponent: React.FC<ConfigProps> = ({config}) => {
const [connected, setConnected] = useState<boolean>(false);
const { state, dispatch } = useGlobalState();
const connection = new HubConnectionBuilder()
.withUrl(`${state.config.url}/${state.config.endpoint}/${state.config.gamingserver}-${state.config.playerid}`) // Replace with your SignalR hub URL
.build();
const connect = async () => {
try {
await connection.start();
setConnected(true);
connection.on("ReceiveMessage", (user: string, message: string) => {
console.log(`${user}: ${message}`);
});
console.log("Connected to SignalR");
} catch (err) {
console.log(`${state.config.url}/${state.config.endpoint}/${state.config.gamingserver}-${state.config.playerid}`)
}
};
const disconnect = async () => {
try {
await connection.stop();
setConnected(false);
console.log("Disconnected from SignalR");
} catch (err) {
console.error("Error disconnecting from SignalR", err);
}
};
return (
<>
{
config.connect ? (<button className='bg-green-200 hover:bg-green-300 text-green-800 font-bold py-2 px-4 rounded' type="submit" onClick={connect}>Connect</button>)
: (<button className='bg-red-200 hover:bg-red-300 text-red-800 font-bold py-2 px-4 rounded' onClick={disconnect}>Disconnect</button>)
}
</>
);
};
export default SignalRComponent;
The withUrl value is input in the form by the user meaning it is dynamic.
When trying to establish a connection I am getting a CORS error
Access to fetch at ‘https://example.co.za/testing/332-4255/negotiate?negotiateVersion=1’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
The issue is not with the server, I have checked.
I have tried the middlewre approach but it is not working, any clue on how to fix this?
Ntando Xakaza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Looks like a typical CORS issue. Since you’re confident the server is set up correctly, here are a couple of things to try:
- Proxy through Next.js: Set up an API route in Next.js to proxy requests and avoid CORS. Something like this:
// pages/api/proxy.ts
export default async (req, res) => {
const response = await fetch(`https://example.co.za/${req.query.endpoint}`, {
method: req.method,
headers: {
...req.headers,
'Origin': undefined // remove the origin header
},
body: req.body
});
const data = await response.json();
res.status(response.status).json(data);
};
- Set withCredentials: true when building the connection in case your server requires it:
const connection = new HubConnectionBuilder()
.withUrl(url, { withCredentials: true })
.build();