Gathering detailed insights and metrics for node-moleculer-web
Gathering detailed insights and metrics for node-moleculer-web
Gathering detailed insights and metrics for node-moleculer-web
Gathering detailed insights and metrics for node-moleculer-web
npm install node-moleculer-web
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (99.66%)
HTML (0.34%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
5 Stars
34 Commits
1 Forks
2 Watchers
2 Branches
1 Contributors
Updated on Jul 11, 2025
Latest Version
1.2.0
Package Id
node-moleculer-web@1.2.0
Unpacked Size
61.16 kB
Size
18.13 kB
File Count
20
NPM Version
10.8.2
Node Version
20.10.0
Published on
Jul 10, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
High-performance web server integration for Moleculer based on uWebSockets.js.
index.d.ts
.1npm install node-moleculer-web
1 Create controller in folder controllers/home.js
1const {AbstractController} = require('node-moleculer-web'); 2class HomeController extends AbstractController { 3 async index() { 4 return `helo world`; 5 } 6} 7module.exports = HomeController
2 Create service in folder services/app.service.js
1const {UwsServer} = require('node-moleculer-web');
2const {Service} = require('moleculer');
3
4const HomeController = require('../controllers/home');
5
6class AppService extends Service {
7 constructor(broker) {
8 super(broker);
9 this.parseServiceSchema({
10 name: 'app',
11 settings: {
12 // base port for server
13 port: process.evn.SERVER_PORT ?? 3101,
14 // on what ip to listen
15 ip: process.evn.SERVER_IP ?? '127.0.0.1',
16
17 portSchema: process.evn.SERVER_SCHEMA ?? 'node',
18 // if statics are not needed, just remove next parameters
19 publicDir: __dirname + '/../public',
20 publicIndex: 'index.html', // or false
21 staticCompress: true, // support compresion gzip, br, deflate
22 staticLastModified: true, // send last modified header for static files
23 // list of controllers
24 controllers: {
25 home: HomeController
26 }
27 },
28 // added mixin UwsServer to current services
29 mixins: [
30 UwsServer
31 ],
32 created: this.createService
33 })
34 }
35
36 createService() {
37 // register routing where home is the controller and index is the method
38 this.createRoute('get / #c:home.index')
39 }
40}
41module.exports = AppService
<request type> / #c:<controller name>.<action>
<request type> / #s:<service name>.<action>
any
- HTTP ALLconnect
- HTTP CONNECTdel
- HTTP DELETEget
- HTTP GEThead
- HTTP HEADoptions
- HTTP OPTIONSpatch
- HTTP PATCHpost
- HTTP POSTput
- HTTP PUTtrace
- HTTP TRACEcache
- second http cacheonBefore(route, req, res)
- Function before call for controller or serviceonAfter(route, req, res, data)
- Function after call for controller or serviceExample options for createRoute
1this.createRoute('get / #c:home.index', {cache: 5});
property | description |
---|---|
requestData | read request data |
cookieData | read/write cookie |
redirectType | "header" | "meta" | "js" (default meta) |
format | default response content type default html |
statusCode | default response http code number 200 |
statusCodeText | default response http code string 200 OK |
requestData or cookieData
(The property objects are available after executing the this.initRequest()
method inside the controller method)
.timer
.start()
— Starts the timer..stop()
— Stops the timer. and Returns elapsed time in milliseconds..initJWT(key, iat = false)
.getJWT()
.createJwtToken(payload = {})
.extractJwtToken(token)
.initRequest()
.readBody()
.asJson(obj, httpCode = 200)
.renderRaw({ view, httpCode, format })
.render({ template, params, httpCode, format })
.setStatus(httpCode)
.writeHeader(key, value)
.setCorsHeaders()
.redirect(location, httpCode = 301)
redirectType
property of the controller.response json object
1class Home extends AbstractController { 2 async index() { 3 return this.asJson({}, 200); 4 } 5}
response redirect to other url
1class Home extends AbstractController { 2 async index() { 3 return this.redirect('https://youdomain.dev', 301); 4 } 5}
response ejs template
1class Home extends AbstractController { 2 async index() { 3 return this.render({ 4 template, params, httpCode: 200, format: 'html' 5 }); 6 } 7}
response raw
1class Home extends AbstractController { 2 async index() { 3 return this.renderRaw({view: 'string', httpCode: 200, format: 'html'}); 4 } 5}
or
1class Home extends AbstractController { 2 async index() { 3 return 'Hello World' 4 } 5}
1const { AbstractController } = require('node-moleculer-web'); 2 3module.exports = class Home extends AbstractController { 4 /** 5 * Initialize request data and cookie handler 6 */ 7 async index() { 8 // Initialize requestData and cookieData 9 this.initRequest(); 10 // 🔍 Read a cookie value, with fallback 11 const cookieValue = this.cookieData.get('my_cookievalue', String(Date.now() /* or 1*new Date() */ )); 12 // ✍️ Set/update the cookie with a new value 13 this.cookieData.set('my_cookievalue', cookieValue); 14 // 📤 Return current cookie value as response 15 return `Current cookie value: ${cookieValue}`; 16 } 17};
1const { AbstractController } = require('node-moleculer-web'); 2 3module.exports = class Home extends AbstractController { 4 /** 5 * Handle GET request and return parsed request data 6 */ 7 async index() { 8 // Initialize request and cookie utilities 9 this.initRequest(); 10 // Extract request data 11 const headers = this.requestData.headers; // All request headers 12 const ip = this.requestData.ip; // Client IP address 13 const query = this.requestData.query ?? {}; // Query parameters 14 const referer = this.requestData.referer; // Referrer URL 15 const currentUrl = this.requestData.url; // Current request URL 16 const userAgent = this.requestData.userAgent; // User-Agent string 17 18 // Return all data as JSON response 19 return this.asJson({ 20 headers, 21 ip, 22 query, 23 referer, 24 currentUrl, 25 userAgent 26 }, 200); 27 } 28};
1const { AbstractController } = require('node-moleculer-web'); 2 3module.exports = class Home extends AbstractController { 4 /** 5 * Calls another microservice and returns the result as JSON 6 */ 7 async index() { 8 try { 9 const data = await this.broker.call('service-name.action', { 10 email: 'test@example.com' 11 }) ?? {}; 12 return this.asJson(data, 200); 13 } catch (error) { 14 return this.asJson({ 15 error: error.message, 16 code: error.code || 500 17 }, error.code || 500); 18 } 19 } 20};
1const { AbstractController } = require('node-moleculer-web'); 2 3module.exports = class Home extends AbstractController { 4 /** 5 * Reads the request body and returns it as JSON 6 */ 7 async index() { 8 try { 9 const body = await this.readBody(); 10 return this.asJson({ body }, 200); 11 12 } catch (error) { 13 return this.asJson({ 14 error: 'Failed to read request body', 15 message: error.message 16 }, 400); 17 } 18 } 19};
1class Home extends AbstractController { 2 // create token 3 async index() { 4 this.initJWT('mykey'); 5 const payload = {userId: 0, status: true}; 6 const token = this.getJWT().create(payload) 7 return this.asJson({token}, 200); 8 } 9 // extract payload for token + validation (is payload not null then token valid) 10 async test() { 11 this.initRequest() 12 const token = this.requestData.query.token ?? ''; 13 this.initJWT('mykey', false); 14 const payload = this.getJWT().extract(token) 15 return this.asJson({payload}, 200); 16 } 17}
Extend rest service
1const {HttpMixin} = require('node-moleculer-web'); 2const {Service} = require('moleculer'); 3class RestService extends Service { 4 constructor(broker) { 5 super(broker); 6 this.parseServiceSchema({ 7 name: 'rest', 8 settings: {}, 9 mixins: [ 10 HttpMixin 11 ], 12 actions: { 13 hello: { 14 rest: 'GET /hello', 15 handler(ctx) { 16 return 'Hello1 API Gateway!' 17 } 18 }, 19 hello2: { 20 rest: 'GET /hello2/:test1/:test2', 21 handler(ctx) { 22 // read request data for meta object 23 console.log('requestData', ctx.meta.requestData) 24 // read cookie 25 ctx.meta.cookieData.get('test', 0); 26 // write cookie 27 ctx.meta.cookieData.set('test', 2); 28 // write header 29 ctx.meta.headers['my-custom-header'] = 'lama'; 30 return 'Hello2 API Gateway!' 31 } 32 }, 33 34 testJson: { 35 rest: 'GET /hello3/test/json', 36 handler(ctx) { 37 return this.asJson(ctx, { 38 myvalue: 111 39 }) 40 } 41 }, 42 43 testRedirect: { 44 rest: 'GET /hello3/test/redirect', 45 handler(ctx) { 46 return this.redirect(ctx, 'https://google.com', 301, 'meta') 47 } 48 } 49 50 }, 51 }); 52 } 53}
1server { 2 listen 80; 3 listen 443 ssl; 4 listen [::]:80; 5 listen [::]:443; 6 7 server_name domain.com; 8 9 location / { 10 proxy_http_version 1.1; 11 proxy_set_header Host $http_host; 12 proxy_set_header X-Real-IP $remote_addr; 13 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 14 proxy_set_header X-NginX-Proxy true; 15 proxy_pass http://127.0.0.1:3001; 16 proxy_redirect off; 17 } 18}
Run locally
1npx moleculer-runner -i 4 services
or
1node node_modules/.bin/moleculer-runner -i 4 services
The config itself
1upstream node_apps { 2 server 127.0.0.1:3001; 3 server 127.0.0.1:3002; 4 server 127.0.0.1:3003; 5 server 127.0.0.1:3004; 6} 7 8server { 9 listen 80; 10 listen 443 ssl; 11 listen [::]:80; 12 listen [::]:443; 13 14 server_name domain.com; 15 16 location / { 17 proxy_http_version 1.1; 18 proxy_set_header Host $http_host; 19 proxy_set_header X-Real-IP $remote_addr; 20 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 21 proxy_set_header X-NginX-Proxy true; 22 proxy_pass http://node_apps; 23 proxy_redirect off; 24 } 25}
cluster config moleculer.config.js
1module.exports = { 2 nodeID: 'DEMO', 3 transporter: "TCP", 4 registry: { 5 // type of call strategy for microservices 6 strategy: "RoundRobin", 7 // If set to true, then each webserver will use only its own micro-services 8 preferLocal: false, 9 }, 10 logger: console 11};
No vulnerabilities found.
No security vulnerabilities found.