or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application.mdcli.mdfunction-nodes.mdhttp-services.mdindex.mdnode-development.mdruntime.mdutilities.md

http-services.mddocs/

0

# HTTP Services

1

2

Express applications and HTTP server integration within Node-RED for building web interfaces, APIs, and HTTP-based nodes. Node-RED provides separate Express apps for editor administration and HTTP node functionality.

3

4

## Capabilities

5

6

### HTTP Admin Application

7

8

Express application serving the Node-RED editor interface and admin API endpoints.

9

10

```javascript { .api }

11

/**

12

* Express application for editor interface and admin API

13

*/

14

const httpAdmin: express.Application;

15

16

/**

17

* Authentication middleware for admin routes

18

*/

19

interface AuthAPI {

20

needsPermission(permission: string): express.RequestHandler;

21

}

22

```

23

24

**Usage Examples:**

25

26

```javascript

27

const RED = require("node-red");

28

const express = require("express");

29

30

// Initialize Node-RED

31

await RED.start();

32

33

// Access admin app

34

const adminApp = RED.httpAdmin;

35

36

// Add custom admin routes

37

adminApp.get("/admin/status", RED.auth.needsPermission("read"), (req, res) => {

38

res.json({

39

version: RED.version,

40

uptime: process.uptime(),

41

flows: RED.runtime.flows.getFlows({}).length

42

});

43

});

44

45

// Add custom middleware to admin app

46

adminApp.use("/admin/custom", express.static("./public"));

47

48

// Integrate with existing Express app

49

const app = express();

50

app.use("/red", RED.httpAdmin);

51

```

52

53

### HTTP Node Application

54

55

Express application for HTTP-based nodes (HTTP In, HTTP Response, etc.) and custom HTTP endpoints.

56

57

```javascript { .api }

58

/**

59

* Express application for HTTP nodes and custom endpoints

60

*/

61

const httpNode: express.Application;

62

```

63

64

**Usage Examples:**

65

66

```javascript

67

const RED = require("node-red");

68

69

// Access HTTP node app

70

const nodeApp = RED.httpNode;

71

72

// Add custom API routes

73

nodeApp.get("/api/data", (req, res) => {

74

res.json({ data: "Custom API response" });

75

});

76

77

// Add middleware for HTTP nodes

78

nodeApp.use("/api", (req, res, next) => {

79

req.customData = "Added by middleware";

80

next();

81

});

82

83

// CORS configuration for HTTP nodes

84

nodeApp.use((req, res, next) => {

85

res.header("Access-Control-Allow-Origin", "*");

86

res.header("Access-Control-Allow-Headers", "Content-Type");

87

next();

88

});

89

90

// Integrate with main app

91

const app = express();

92

app.use("/node-red", RED.httpNode);

93

```

94

95

### HTTP Server Access

96

97

Direct access to the underlying HTTP server instance used by Node-RED.

98

99

```javascript { .api }

100

/**

101

* HTTP server instance used by Node-RED

102

*/

103

const server: http.Server;

104

```

105

106

**Usage Examples:**

107

108

```javascript

109

const RED = require("node-red");

110

const WebSocket = require("ws");

111

112

// Access server instance

113

const server = RED.server;

114

115

// Add WebSocket server

116

const wss = new WebSocket.Server({ server });

117

118

wss.on('connection', (ws) => {

119

console.log('WebSocket client connected');

120

121

ws.on('message', (message) => {

122

console.log('Received:', message);

123

ws.send('Echo: ' + message);

124

});

125

});

126

127

// Get server information

128

console.log(`Server listening on port: ${server.address().port}`);

129

130

// Add server event listeners

131

server.on('upgrade', (request, socket, head) => {

132

console.log('HTTP upgrade request received');

133

});

134

```

135

136

### Custom HTTP Node Integration

137

138

Patterns for creating HTTP-based nodes that integrate with Node-RED's HTTP infrastructure.

139

140

```javascript { .api }

141

/**

142

* HTTP node registration pattern

143

*/

144

function HttpBasedNode(config) {

145

RED.nodes.createNode(this, config);

146

147

const node = this;

148

const path = config.path || "/api/mynode";

149

150

// Register HTTP endpoint

151

RED.httpNode.get(path, (req, res) => {

152

// Create message from HTTP request

153

const msg = {

154

_msgid: RED.util.generateId(),

155

req: req,

156

res: res,

157

payload: req.query,

158

topic: "http-request"

159

};

160

161

// Send to node's output

162

node.send(msg);

163

164

// Response will be sent by HTTP Response node

165

// or you can send response directly:

166

// res.json({ status: "ok" });

167

});

168

169

// Handle messages from flow

170

node.on('input', function(msg, send, done) {

171

// Process message and send HTTP response if res object exists

172

if (msg.res && !msg.res.headersSent) {

173

msg.res.json({

174

processed: msg.payload,

175

timestamp: Date.now()

176

});

177

}

178

179

done();

180

});

181

182

// Clean up routes on node removal

183

node.on('close', function(removed, done) {

184

// Remove HTTP routes (Node-RED handles this automatically)

185

done();

186

});

187

}

188

```

189

190

### HTTP Authentication Integration

191

192

Integration with Node-RED's authentication system for HTTP services.

193

194

```javascript { .api }

195

/**

196

* Authentication methods

197

*/

198

interface AuthenticationAPI {

199

/** Check if user has specific permission */

200

needsPermission(permission: string): express.RequestHandler;

201

/** Extract user from request */

202

getUser(req: express.Request): UserObject | null;

203

}

204

205

/**

206

* Available permissions

207

*/

208

type Permission =

209

| "read" // Read access to editor and flows

210

| "write" // Write access to modify flows

211

| "*" // Full admin access

212

| "admin" // Administrative functions

213

| "audit"; // Audit log access

214

```

215

216

**Authentication Examples:**

217

218

```javascript

219

const RED = require("node-red");

220

221

// Protect admin routes

222

RED.httpAdmin.get("/admin/sensitive",

223

RED.auth.needsPermission("admin"),

224

(req, res) => {

225

res.json({ message: "Admin only data" });

226

}

227

);

228

229

// Protect HTTP node routes

230

RED.httpNode.get("/api/protected",

231

RED.auth.needsPermission("read"),

232

(req, res) => {

233

const user = RED.auth.getUser(req);

234

res.json({

235

message: "Protected data",

236

user: user ? user.username : "anonymous"

237

});

238

}

239

);

240

241

// Custom authentication middleware

242

RED.httpNode.use("/api/custom", (req, res, next) => {

243

const apiKey = req.headers['x-api-key'];

244

245

if (!apiKey || !validateApiKey(apiKey)) {

246

return res.status(401).json({ error: "Invalid API key" });

247

}

248

249

next();

250

});

251

```

252

253

### Static File Serving

254

255

Serve static files through Node-RED's HTTP infrastructure.

256

257

```javascript { .api }

258

/**

259

* Static file serving patterns

260

*/

261

// Serve static files from custom directory

262

RED.httpNode.use("/static", express.static("./public"));

263

264

// Serve files with caching headers

265

RED.httpNode.use("/assets", express.static("./assets", {

266

maxAge: "1d",

267

etag: true

268

}));

269

270

// Conditional static serving

271

RED.httpAdmin.use("/admin/assets", (req, res, next) => {

272

if (req.user && req.user.permissions.includes("admin")) {

273

express.static("./admin-assets")(req, res, next);

274

} else {

275

res.status(403).send("Forbidden");

276

}

277

});

278

```

279

280

### HTTPS and SSL

281

282

Configuration for secure HTTP services.

283

284

```javascript { .api }

285

/**

286

* HTTPS configuration in settings

287

*/

288

interface HttpsSettings {

289

https: {

290

key: string | Buffer;

291

cert: string | Buffer;

292

ca?: string | Buffer;

293

passphrase?: string;

294

};

295

}

296

```

297

298

**HTTPS Example:**

299

300

```javascript

301

const fs = require("fs");

302

const RED = require("node-red");

303

304

// Initialize with HTTPS

305

RED.init({

306

https: {

307

key: fs.readFileSync("private-key.pem"),

308

cert: fs.readFileSync("certificate.pem")

309

},

310

uiPort: 1880

311

});

312

313

// Server will be HTTPS

314

RED.start().then(() => {

315

console.log("Node-RED started with HTTPS");

316

console.log("Editor: https://localhost:1880");

317

});

318

```

319

320

### WebSocket Integration

321

322

Integration patterns for WebSocket communication alongside HTTP services.

323

324

```javascript { .api }

325

/**

326

* WebSocket integration with Node-RED HTTP server

327

*/

328

const WebSocket = require("ws");

329

330

// Create WebSocket server using Node-RED's HTTP server

331

const wss = new WebSocket.Server({

332

server: RED.server,

333

path: "/ws"

334

});

335

336

// Handle WebSocket connections

337

wss.on('connection', (ws, req) => {

338

console.log('WebSocket connected from:', req.connection.remoteAddress);

339

340

// Integrate with Node-RED flows

341

ws.on('message', (data) => {

342

const msg = {

343

_msgid: RED.util.generateId(),

344

payload: JSON.parse(data),

345

topic: "websocket",

346

websocket: ws

347

};

348

349

// Send to flow (you would register this in a custom node)

350

// RED.events.emit("websocket-message", msg);

351

});

352

353

ws.on('close', () => {

354

console.log('WebSocket disconnected');

355

});

356

});

357

```

358

359

## Configuration Examples

360

361

### Complete HTTP Integration

362

363

```javascript

364

const express = require("express");

365

const http = require("http");

366

const RED = require("node-red");

367

368

// Create Express app and HTTP server

369

const app = express();

370

const server = http.createServer(app);

371

372

// Initialize Node-RED

373

RED.init(server, {

374

httpAdminRoot: "/admin",

375

httpNodeRoot: "/api",

376

userDir: "./node-red-data",

377

uiPort: 3000

378

});

379

380

// Start Node-RED

381

RED.start().then(() => {

382

// Add custom routes

383

app.get("/", (req, res) => {

384

res.send("Node-RED Integration Example");

385

});

386

387

// Mount Node-RED apps

388

app.use("/admin", RED.httpAdmin);

389

app.use("/api", RED.httpNode);

390

391

// Start server

392

server.listen(3000, () => {

393

console.log("Server running on port 3000");

394

console.log("Node-RED editor: http://localhost:3000/admin");

395

console.log("Node-RED API: http://localhost:3000/api");

396

});

397

});

398

```

399

400

## Types

401

402

```javascript { .api }

403

interface UserObject {

404

username: string;

405

permissions: string[];

406

[key: string]: any;

407

}

408

409

interface HttpsSettings {

410

key: string | Buffer;

411

cert: string | Buffer;

412

ca?: string | Buffer;

413

passphrase?: string;

414

}

415

```