TypeError: server.on is not a function

Hello, node-heads :slight_smile: I'm installing node-red in a nest.js app and I'm getting the following error when running/starting the server. I have no clue how to fix this issue and documentation for nest.js apps is quite scarce. Any help is highly appreciated...

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { json } from 'express';

async function bootstrap() {
	const app = await NestFactory.create(AppModule);
	app.enableCors();
	app.use(json({ limit: '50mb' }));

	const config = new DocumentBuilder()
		.setTitle('OAST')
		.setDescription('The OAST API description')
		.setVersion('0.1')
		.build();

	const document = SwaggerModule.createDocument(app, config);
	SwaggerModule.setup('api', app, document);

	/**
	 * Configure node-red
	 */
	const httpAdapter = app.getHttpAdapter();
	const RED = require('node-red');

	// Settings object for node-red
	const nodeRedSettings = {
		httpAdminRoot: '/red',
		httpNodeRoot: '/api',
		userDir: '/home/nol/.nodered/',
		functionGlobalContext: {}, // enables global context
	};

	RED.init(httpAdapter, nodeRedSettings);
	// Serve the editor UI from /red
	app.use(nodeRedSettings.httpAdminRoot, RED.httpAdmin);
	// Serve the http nodes UI from /api
	app.use(nodeRedSettings.httpNodeRoot, RED.httpNode);

	await app.listen(3001);

	// Start the runtime
	RED.start();
}
bootstrap();

Node-RED expects the server object it is given to be an instance of express. I know very little about nest.js, but it does appear to be able to wrap express somehow. The question is whether you are doing that and are you getting ahold of an express instance when you call getHttpAdapter.

I also note you have userDir set to /home/nol/.nodered/ .... Make sure you change that to something suitable for your setup, unless of course you also have a user called nol like I do...

1 Like

Thank you. Yes, nest.js is an Express MVC wrapper... I had to google how to get a hold of the app instance, I'll dig deeper, maybe the const httpAdapter = app.getHttpAdapter(); is not the Express server object, maybe it's wrapped and the on function isn't mapped... or something...

This worked, thank you.

const httpAdapter = app.getHttpAdapter();
const appInstance = httpAdapter.getInstance();

// Settings object for node-red
const nodeRedSettings = {
		functionGlobalContext: {}, // enables global context
		httpAdminRoot: '/red',
		httpNodeRoot: '/api',
		userDir: '/home/nol/.nodered/',
	};

RED.init(appInstance, nodeRedSettings);
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.