Skip to content

BE_5 - Socket.IO Server Setup #11

@notjackl3

Description

@notjackl3

Summary

Create custom Next.js server with Socket.IO integration and Redis adapter for WebSocket connections.
[Estimated hours: 9-10]

Objectives

  • Create custom server file (src/server.ts)
  • Integrate Socket.IO with Next.js
  • Configure Redis adapter for horizontal scaling
  • Add authentication middleware for WebSocket
  • Set up basic connection/disconnection handlers
  • Update package.json scripts

Description

Next.js doesn't natively support WebSocket servers, so we need a custom server that runs both the Next.js app and Socket.IO. The Redis adapter ensures that Socket.IO events work across multiple server instances (important for production scaling).

Technical Details

File Structure

src/
├── server.ts                    # Custom server
├── socket/
│   ├── index.ts                # Socket.IO setup
│   ├── middleware/
│   │   └── auth.ts             # WebSocket auth
│   └── types.ts                # Event type definitions

Authentication Flow

  1. Client connects with JWT token in handshake
  2. Middleware validates token (use NextAuth.js session)
  3. Attach user data to socket.data.user
  4. Reject connection if invalid

Acceptance Criteria

  • npm run dev starts both Next.js and Socket.IO server
  • Can access Next.js at http://localhost:3000
  • Can connect to WebSocket at ws://localhost:3000
  • Redis adapter configured (verify with multiple server instances)
  • Authentication middleware blocks unauthenticated connections
  • Authenticated users can connect successfully
  • Connection/disconnection events logged
  • TypeScript types defined for all Socket.IO events

Resources

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions