Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: metatype is not a constructor when using instance of own HTTPS Server class

Tags:

node.js

nestjs

Good evening, I am playing around with nest and want to achieve an own HTTPS-Server that can be instantiated everywhere in other projects. Right at the beginning I get the following error-message:

TypeError: metatype is not a constructor

… when I init the following HTTPS-Server:

import { Injectable } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import * as fs from 'fs';

@Injectable()
export class HttpsServer {

    constructor() {}

    async bootstrap() {
        const httpsOptions = {
            key: fs.readFileSync('./certs/server.key'),
            cert: fs.readFileSync('./certs/server.cert'),
        };
        const app = await NestFactory.create<NestFastifyApplication>(
            new FastifyAdapter({ https: httpsOptions }),
        );

        await app.listen(443);
    }
}

like this:

import { Logger } from '@nestjs/common';
import { HttpsServer } from 'server-lib';

const logger = new Logger();
const app = new HttpsServer();

app.bootstrap().then(() => {
  logger.log('Bootstrap complete!');
}).catch((error) => {
  logger.log('Bootstrap failed: ', error);
  process.exit(1);
});

Thx for help...

like image 556
meDom Avatar asked Sep 14 '25 22:09

meDom


2 Answers

You probably have used an incorrect guard. Check @UseGuards() and use the correct guard for that function.

like image 75
mhmmdamiwn Avatar answered Sep 17 '25 13:09

mhmmdamiwn


All Nest applications needs to have a "RootModule" of some sort. With nest new applications this is a AppModule. This class holds the metadata for the server for how to tie everything together and run. What you could probably do is modify your HttpModule's constructor to do something like

export class HttpsServer {

    constructor(private readonly rootModule: Type<any>) {} // Type comes from @nestjs/common

    async bootstrap() {
        const httpsOptions = {
            key: fs.readFileSync('./certs/server.key'),
            cert: fs.readFileSync('./certs/server.cert'),
        };
        const app = await NestFactory.create<NestFastifyApplication>(
            this.rootModule, 
            new FastifyAdapter({ https: httpsOptions }),
        );

        await app.listen(443);
    }
}

So now when you call new HttpServer() you pass in the root module and have everything else already set up. The NestFactory will instantiate the metadata from there properly, and you'll use the FastifyAdapter.

For more information, I suggest you follow the docs overview to get a feeling of how these classes fit together and why they're needed.

like image 23
Jay McDoniel Avatar answered Sep 17 '25 12:09

Jay McDoniel