or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client.mdconnection.mdframe.mdindex.mdrouter-request.mdserver.mdutilities.md

router-request.mddocs/

0

# Router Request Handling

1

2

Router-specific request handling providing path and protocol-based routing capabilities with simplified request processing within the router context.

3

4

## Capabilities

5

6

### WebSocketRouterRequest

7

8

Represents a WebSocket request within a router context, providing a simplified interface for route handlers.

9

10

```javascript { .api }

11

/**

12

* WebSocket request within router context

13

* @param webSocketRequest - Original WebSocketRequest

14

* @param resolvedProtocol - Resolved protocol for this route

15

*/

16

class WebSocketRouterRequest extends EventEmitter {

17

/**

18

* Accept the connection

19

* @param origin - Origin to include in response

20

* @param cookies - Array of cookie objects to set

21

* @returns WebSocketConnection instance

22

*/

23

accept(origin?: string, cookies?: Cookie[]): WebSocketConnection;

24

25

/**

26

* Reject the connection

27

* @param status - HTTP status code (default: 403)

28

* @param reason - Rejection reason string

29

* @param extraHeaders - Additional HTTP headers

30

*/

31

reject(status?: number, reason?: string, extraHeaders?: object): void;

32

33

/** Original WebSocketRequest */

34

readonly webSocketRequest: WebSocketRequest;

35

36

/** Resolved protocol for this route */

37

readonly protocol: string;

38

39

/** Origin header value */

40

readonly origin: string;

41

42

/** Requested resource path */

43

readonly resource: string;

44

45

/** Parsed URL object */

46

readonly resourceURL: URL;

47

48

/** Original HTTP request object */

49

readonly httpRequest: http.IncomingMessage;

50

51

/** Client IP address */

52

readonly remoteAddress: string;

53

54

/** Requested WebSocket version */

55

readonly webSocketVersion: number;

56

57

/** Array of requested extension objects */

58

readonly requestedExtensions: object[];

59

60

/** Array of parsed cookie objects */

61

readonly cookies: Cookie[];

62

}

63

```

64

65

**Events:**

66

67

- `'requestAccepted'` - `(WebSocketConnection)` - Request accepted

68

- `'requestRejected'` - `(WebSocketRouterRequest)` - Request rejected

69

70

**Usage Example:**

71

72

```javascript

73

const WebSocket = require('websocket');

74

const http = require('http');

75

76

// Create HTTP server and WebSocket server

77

const httpServer = http.createServer();

78

httpServer.listen(8080);

79

80

const wsServer = new WebSocket.server({

81

httpServer: httpServer,

82

autoAcceptConnections: false

83

});

84

85

// Create router

86

const router = new WebSocket.router({

87

server: wsServer

88

});

89

90

// Route chat requests

91

router.mount('/chat', 'chat-protocol', function(request) {

92

console.log('Chat request from:', request.origin);

93

console.log('Resource:', request.resource);

94

console.log('Protocol:', request.protocol);

95

96

// Validate request

97

if (!isOriginAllowed(request.origin)) {

98

request.reject(403, 'Origin not allowed');

99

return;

100

}

101

102

// Accept connection

103

const connection = request.accept(request.origin, [

104

{ name: 'sessionId', value: 'chat123', httponly: true }

105

]);

106

107

console.log('Chat connection established');

108

109

// Handle chat messages

110

connection.on('message', function(message) {

111

if (message.type === 'utf8') {

112

console.log('Chat message:', message.utf8Data);

113

// Broadcast to other chat clients

114

broadcastToChatClients(message.utf8Data);

115

}

116

});

117

});

118

119

// Route API requests with wildcard

120

router.mount('/api/*', '*', function(request) {

121

console.log('API request:', request.resource);

122

console.log('Requested protocols:', request.webSocketRequest.requestedProtocols);

123

124

// Accept any protocol for API

125

const connection = request.accept();

126

127

// Handle API communication

128

connection.on('message', function(message) {

129

if (message.type === 'utf8') {

130

try {

131

const apiCall = JSON.parse(message.utf8Data);

132

handleApiCall(connection, apiCall);

133

} catch (e) {

134

connection.close(1003, 'Invalid JSON');

135

}

136

}

137

});

138

});

139

140

// Catch-all route for unhandled requests

141

router.mount('*', '*', function(request) {

142

console.log('Unhandled request to:', request.resource);

143

request.reject(404, 'Not found');

144

});

145

146

function isOriginAllowed(origin) {

147

// Implement origin validation logic

148

return origin === 'http://localhost:3000' || origin === 'https://example.com';

149

}

150

151

function broadcastToChatClients(message) {

152

// Implement chat broadcasting logic

153

wsServer.connections.forEach(function(connection) {

154

if (connection.connected) {

155

connection.sendUTF(message);

156

}

157

});

158

}

159

160

function handleApiCall(connection, apiCall) {

161

// Implement API call handling

162

const response = {

163

id: apiCall.id,

164

result: 'API response for: ' + apiCall.method

165

};

166

connection.sendUTF(JSON.stringify(response));

167

}

168

```

169

170

### Advanced Router Request Handling

171

172

**Protocol Resolution:**

173

174

```javascript

175

// The router resolves protocols based on the route definition

176

router.mount('/specific', 'exact-protocol', function(request) {

177

// request.protocol will be 'exact-protocol'

178

console.log('Resolved protocol:', request.protocol);

179

});

180

181

router.mount('/any-protocol', '*', function(request) {

182

// request.protocol will be the first requested protocol by client

183

console.log('Client requested protocols:', request.webSocketRequest.requestedProtocols);

184

console.log('Resolved protocol:', request.protocol);

185

});

186

```

187

188

**Request Information Access:**

189

190

```javascript

191

router.mount('/debug', '*', function(request) {

192

console.log('Request details:');

193

console.log(' Resource:', request.resource);

194

console.log(' Origin:', request.origin);

195

console.log(' Remote Address:', request.remoteAddress);

196

console.log(' WebSocket Version:', request.webSocketVersion);

197

console.log(' Extensions:', request.requestedExtensions);

198

console.log(' Cookies:', request.cookies);

199

console.log(' Headers:', request.httpRequest.headers);

200

201

const connection = request.accept();

202

// Handle connection...

203

});

204

```

205

206

**Error Handling:**

207

208

```javascript

209

router.mount('/secure', 'secure-protocol', function(request) {

210

try {

211

// Validate authentication

212

const authHeader = request.httpRequest.headers.authorization;

213

if (!authHeader || !validateToken(authHeader)) {

214

request.reject(401, 'Unauthorized');

215

return;

216

}

217

218

// Validate SSL

219

if (!request.httpRequest.connection.encrypted) {

220

request.reject(400, 'SSL required');

221

return;

222

}

223

224

const connection = request.accept();

225

226

connection.on('error', function(error) {

227

console.error('Connection error:', error);

228

});

229

230

} catch (error) {

231

console.error('Route handler error:', error);

232

request.reject(500, 'Internal server error');

233

}

234

});

235

```

236

237

## Types

238

239

### Cookie Object

240

241

```javascript { .api }

242

interface Cookie {

243

name: string;

244

value: string;

245

path?: string;

246

domain?: string;

247

expires?: Date;

248

maxage?: number;

249

secure?: boolean;

250

httponly?: boolean;

251

}

252

```