-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
58 lines (49 loc) · 1.51 KB
/
server.ts
File metadata and controls
58 lines (49 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// server.ts - Next.js Standalone + Socket.IO
import { setupSocket } from '@/lib/socket';
import { createServer } from 'http';
import { Server } from 'socket.io';
import next from 'next';
const dev = process.env.NODE_ENV !== 'production';
const currentPort = 3000;
const hostname = '0.0.0.0';
// Custom server with Socket.IO integration
async function createCustomServer() {
try {
// Create Next.js app
const nextApp = next({
dev,
dir: process.cwd(),
// In production, use the current directory where .next is located
conf: dev ? undefined : { distDir: './.next' }
});
await nextApp.prepare();
const handle = nextApp.getRequestHandler();
// Create HTTP server that will handle both Next.js and Socket.IO
const server = createServer((req, res) => {
// Skip socket.io requests from Next.js handler
if (req.url?.startsWith('/api/socketio')) {
return;
}
handle(req, res);
});
// Setup Socket.IO
const io = new Server(server, {
path: '/api/socketio',
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
setupSocket(io);
// Start the server
server.listen(currentPort, hostname, () => {
console.log(`> Ready on http://${hostname}:${currentPort}`);
console.log(`> Socket.IO server running at ws://${hostname}:${currentPort}/api/socketio`);
});
} catch (err) {
console.error('Server startup error:', err);
process.exit(1);
}
}
// Start the server
createCustomServer();