The ServerInstance class is designed to provide a singleton instance of a server with integrated features for handling HTTP requests, WebSocket communication, MongoDB connections, and JWT-based authentication. It follows the Singleton pattern, ensuring that only one instance of the class is created throughout the application.

Class Members

1. database: MongoClient

Property that can store an instance of the MongoDB MongoClient class. This property is intended for managing connections to a MongoDB database, facilitating data storage and retrieval.

2. httpServer: http.Server

An instance of the Node.js http.Server class, responsible for handling HTTP requests. It provides the core infrastructure for routing and responding to client requests.

3. io: Server

An instance of the Server class from the library. It enables bidirectional communication between clients and the server through WebSockets, fostering real-time updates and interactive features.

4. app: express.Express

An instance of the Express.js application. Express simplifies the process of defining routes, middleware, and handling HTTP requests, making it an essential component for building scalable and modular web applications.

5. port: number = 8081

The port number on which the server listens for incoming HTTP requests. The default port is set to 8081, but it can be modified to suit the application's deployment environment.

6. functions: any = {}

An object that serves as a placeholder for storing various functions. This allows developers to extend and customize server functionality by adding their own methods and utilities.

7. Auth

An object containing authentication-related properties.

auth = {
    jwtSecret: '****@q$aAinTS',
    jwtSignOpts: {
        expiresIn: '1d',
    createCookieOptions: () => {
        return {
            expires: moment.utc().add(23, 'hours').toDate()

8. jwtSecret: string

A secret key used for generating and verifying JSON Web Tokens (JWTs). This key is critical for securing user authentication and authorization processes.

9. jwtSignOpts: object

Options for signing JWTs, including configurations such as the expiration time (expiresIn). JWTs play a vital role in maintaining user sessions securely.

10. createCookieOptions(): object

A function that generates options for creating cookies. These options may include expiration times, domain specifications, and other configurations essential for secure cookie-based authentication.

Here is the example for setting authentication in cookie while login.

ServerInstance.getInstance().auth.createCookieOptions = () => ({
    expires: moment.utc().add(23, 'hours').toDate(),
    sameSite: 'none',
    secure: true

export default createBackendFunction(async function () {
    // Login logic here

Last updated