Based on the error message you're receiving, it appears you're encountering a WebSocket connection issue when trying to connect to Deepgram's API from a Next.js application. Let's analyze the problem and provide some potential solutions.
-
Authentication Issue:
The most common reason for a WebSocket connection to be refused is an authentication problem. In your code, you're not including the API key in the WebSocket connection URL. Deepgram requires authentication for WebSocket connections.
-
CORS (Cross-Origin Resource Sharing) Issue:
While your server-side code sets CORS headers, these don't apply to WebSocket connections. Ensure your client-side code is connecting from an allowed origin.
-
Incorrect WebSocket URL:
Make sure you're using the correct WebSocket URL for Deepgram's API.
Here are some steps to troubleshoot and potentially resolve the issue:
- Include API Key in WebSocket Connection:
When establishing the WebSocket connection, you need to include your Deepgram API key in the request headers. Here's an example of how to do this:
const socket = new WebSocket('wss://api.deepgram.com/v1/listen?model=nova-2&language=vi-VN&smart_format=true&encoding=webm&channels=1&sample_rate=16000&interim_results=true&punctuate=true', {
headers: {
Authorization: `Token ${YOUR_DEEPGRAM_API_KEY}`
}
});
-
Check API Key:
Ensure that your Deepgram API key is valid and has the necessary permissions.
-
Verify WebSocket Support:
Confirm that your hosting environment supports WebSocket connections.
-
Use Deepgram SDK:
Consider using the official Deepgram SDK for JavaScript, which handles authentication and connection details for you. You can find more information in the Deepgram SDK documentation.