I am trying to deploy a WebSocket for my application on Azure App Service.
My application uses Next.js 14 with the App Router, and I have built a separate server to handle upgrade requests.
// server.ts
// run server by
// `tsx server.ts`
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
async function startServer() {
try {
await app.prepare();
const server = createServer((req, res) => {
const parsedUrl = parse(req.url!, true);
handle(req, res, parsedUrl);
});
wsHandler.createWebSocketServer();
if (!wsHandler.wss) {
throw new Error('Can not create WebSocket server');
}
// Xử lý WebSocket
server.on('upgrade', (request, socket, head) => {
console.log('Upgrade request received:', {
url: request.url,
time: new Date().toISOString(),
});
const parsedUrl = parse(request.url!, true);
if (
['/_next/webpack-hmr', '/api/xxx'].includes(parsedUrl.pathname || '')
) {
if (parsedUrl.pathname === '/api/xxx') {
wsHandler.wss?.handleUpgrade(request, socket, head, (ws) => {
wsHandler.wss?.emit('connection', ws, request);
});
}
} else {
socket.destroy();
}
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`> Server running at http://localhost:${PORT}`);
});
} catch (err) {
console.error('Error init server:', err);
process.exit(1);
}
}
startServer();
Everything worked fine locally, but it crashes when deploying to Azure App Service. Debugging concluded that the request did not reach the server running in Azure App Service, indicating that the request was blocked somewhere.
Here is the information about my Azure App Service settings:
- Operating System: Linux
- Node.js Version: 20
- Service Plan: Premium v3 (P0v3)
- Inbound Traffic Configuration: Public network access enabled with no access restrictions
- App Assigned Address: Not configured
- Private Endpoints: 0 private endpoints
- Optional Inbound Services: Azure Front Door: View details (it seems not set because clicking redirects to the create page)
The website still works fine with the server.ts file, only the websocket request is not received and fails