Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Node.js Hosting Europe - HostForLIFE.eu :: When and How to Use Session vs. Token-Based Authentication in MERN?

clock July 30, 2025 07:37 by author Peter

The cornerstone of online application security is authentication. The authentication environment in MERN (MongoDB, Express.js, React, and Node.js) stack apps is dominated by two popular methods: two methods of authentication: session-based and token-based. Although they both accomplish the same objective—verifying a user's identity and safeguarding resources their implementation, application cases, and scalability are very different. This page describes each approach, how it functions in a MERN setting, and why it is better to use one over the other.

What is Authentication?
Before we dive in, let’s clarify.

  • Authentication: confirming the identity of the user (Are you who you say you are?)
  • Authorization: controlling access to resources (What can you do now that you're authenticated?)

Overview of Authentication Methods

Method Session-Based Authentication Token-Based Authentication
Storage Server-side (in memory or DB) Client-side (usually in localStorage or cookies)
Identity Proof Session ID (stored in cookie) JWT (JSON Web Token)
Stateless/Stateful Stateful Stateless
Scalability Less scalable unless using session store More scalable
Common Use Cases Traditional web apps SPAs, mobile apps, microservices

Session-Based Authentication (Cookie-Based)

How does it work?

  • User submits credentials via lthe ogin form.
  • Backend verifies and creates a session, saving it on the server (in memory, Redis, or DB).
  • Server returns a session ID in a secure HTTP-only cookie.
  • On each request, the browser sends the session ID via cookie.
  • Server looks up session data using the ID and verifies the user.

Where does it fit in MERN?

  • React: The frontend sends login requests and automatically includes cookies on future requests (if configured correctly).
  • Express/Node.js: Stores sessions using express-session or similar libraries.
  • MongoDB: Often used with a session store like connect-mongo.

Security Features

  • HttpOnly cookies protect against XSS.
  • Cookies can be set to SameSite, Secure, and have expiry times.

Drawbacks

  • Needs server-side storage (memory or DB).
  • Less ideal for horizontal scaling unless using a centralized session store (e.g., Redis).
  • Slightly more complex to manage in APIs for SPAs or mobile apps.

Token-Based Authentication (JWT)
How does it work?

  • User logs in with credentials.
  • Server verifies and returns a signed token (usually JWT).
  • Token is stored on the client (localStorage, sessionStorage, or cookie).
  • On each request, a token is sent in headers (commonly in Authorization: Bearer <token>).
  • Server validates token signature and grants access.

Where does it fit in MERN?

  • React: Stores token in localStorage or cookies, attaches it to API requests using Axios or Fetch.
  • Express/Node.js: Verifies token with jsonwebtoken or similar libraries.
  • MongoDB: Optionally stores refresh tokens for session control.

Security Features

  • Tokens can be signed with a secret or private key.
  • Supports token expiration (exp), issued at (iat), and more.

Drawbacks

  • If stored in localStorage, vulnerable to XSS attacks.
  • No built-in logout mechanism (tokens are self-contained).
  • Revocation is difficult without additional mechanisms (blacklists, short expiration with refresh tokens).

Comparison Table

Feature Session-Based Token-Based (JWT)
Storage Server-side (in-memory, Redis, DB) Client-side (localStorage, cookie)
Stateless No (unless using JWT in session) Yes
Suitable for SPAs With extra setup Best choice
Mobile Compatibility Harder (no cookie support) Very good
CSRF Protection (if using cookies) Requires manual implementation
XSS Risk Safer (HttpOnly cookies) Risky if using localStorage
Logout Server clears the session Token must expire or be blacklisted
Performance Lookup needed on each request No DB lookup if using stateless JWTs
Token Revocation Easy (delete session) Complex (blacklist, refresh tokens)

When to Use What?

Use Session-Based Authentication When

  • You’re building a server-rendered web app (e.g., admin dashboard).
  • You control both client and server and want automatic cookie handling.
  • You need simple session invalidation (e.g., logging users out remotely).
  • You can scale horizontally with a session store like Redis.

Use Token-Based Authentication (JWT) When?

  • You’re building a single-page application (SPA) with React.
  • You want to support mobile apps or third-party clients.
  • You prefer a stateless API that’s easy to scale.
  • You want users to remain authenticated across multiple domains/services (microservices).

Session + Token Hybrid Approach (Best of Both Worlds)
Many modern apps use a hybrid approach.

  • Store the JWT in an HttpOnly cookie (safer from XSS).
  • Use refresh tokens with short-lived access tokens.
  • Server can keep track of refresh tokens to allow logout.

This combines the statelessness of tokens with the security of sessions.

Final Thoughts

There’s no one-size-fits-all approach to authentication in the MERN stack. Your decision depends on.

  • Application type (SPA, mobile, or SSR).
  • Security requirements.
  • Scalability and infrastructure.
  • Developer experience and ease of maintenance.

Both session-based and token-based auth systems have matured. The best strategy in 2025 is to choose consciously based on your application’s architecture and implement it securely.

Conclusion
In the evolving world of full-stack development, especially in MERN applications, choosing the right authentication method is crucial for performance, security, and user experience. Session-based authentication remains reliable for traditional web apps where server-side session control is preferred. On the other hand, token-based authentication (JWT) is ideal for modern, stateless, API-driven applications like SPAs and mobile apps.

By understanding the trade-offs between these two approaches, developers can design authentication systems that are secure, scalable, and user-friendly. In many real-world scenarios, a hybrid approach combining short-lived tokens with secure cookies offers the best balance between security and flexibility.

Ultimately, the best choice is not about which method is superior - it's about which method aligns with your architecture, user experience goals, and scalability needs.

 



Node.js Hosting Europe - HostForLIFE.eu :: What is the architecture of Node.js?

clock July 14, 2025 08:04 by author Peter

It's likely that Node.js is responsible for any websites that load really quickly or change in real time, such as chat apps or live scores. However, what is Node.js and how does its architecture contribute to its power? Let's put it in plain language.

What is Node.js?
Node.js is not a programming language or a framework; it’s a runtime environment. It enables developers to run JavaScript on the server side, outside of the browser. It’s built on Google Chrome’s V8 JavaScript engine, which makes it super fast.

e.g: "Hello World" in Node.js.
// Import the built-in 'http' module
const http = require('http');

// Create a simple server
const server = http.createServer((req, res) => {
  res.end('Hello World from Node.js!');
});

// Server listens on port 3000
server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

This simple server handles HTTP requests using a single thread and responds with "Hello World". Even if 100 users open it at once, Node.js can manage that efficiently, thanks to its architecture.

Let’s break it down.

1. Single-Threaded Event Loop

Node.js uses a single thread to handle all client requests. That means it doesn’t create a new thread for every request like traditional web servers (such as Apache). Here the question comes.

Then, how does it handle multiple users simultaneously?

It supports multiple users simultaneously through its Event-Driven Architecture. Let's explore it.

2. Event-Driven Architecture

Imagine you are at a restaurant. Instead of the chef cooking only one dish at a time (waiting for it to finish before starting the next), he puts dishes in the oven and moves on to the next task. When the oven beeps, he knows the food is ready.

Our Node.js works in the same way.

  • When a request (like fetching data or reading a file) comes in, it’s added to the event queue.
  • Node.js doesn’t wait for the task to finish. Instead, it moves on to the next task.
  • Once the task is completed, Node.js receives notification (via a callback function) and processes the result.

This makes Node.js extremely fast and efficient, particularly for I/O-Intensive tasks.

  • Reading/writing files
  • Talking to databases
  • Calling APIs

3. Non-Blocking I/O

  • Most web servers use blocking I/O, which means they wait for one operation to finish before moving to the next.
  • Node.js uses non-blocking I/O, meaning it doesn’t wait for input. This allows Node.js to handle thousands of requests per second with a single thread.

Let's simulate a non-blocking operation, such as reading a file.
const fs = require('fs');

console.log('Start reading file...');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  console.log('File content:', data);
});

console.log('Reading file initiated...');


Output

Key Components of Node.js Architecture
Here are the main parts that makeup Node.

Components Role

V8 Engine

Converts JavaScript code into machine code. It’s fast and powerful.

Libuv

A library that provides the event loop and handles asynchronous operations.

Event Loop

Keeps checking for completed tasks and runs their callback functions.

CallBacks

Functions that are executed when a task finishes.

APIs

Node.js provides APIs for file systems, networks, and more.

Advantages of Node.js Architecture
Fast: Thanks to V8 and the non-blocking model.

  • Scalable: Handles a large number of users without crashing or slowing down.
  • Efficient: Great for real-time apps like chat, games, or live data.
  • Lightweight: Uses fewer system resources compared to traditional servers.

When to Use Node.js?
Node.js is ideal for.

  • Real-time apps (chat apps, online games)
  • APIs for web/mobile apps
  • Data streaming apps
  • Single Page Applications (SPAs)

Conclusion
Node.js architecture is what makes it stand out. Its event-driven, non-blocking, and single-threaded design helps developers build fast, scalable, and efficient applications.

HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Node.js Hosting Europe - HostForLIFE.eu :: Installing NVS on Windows Machine

clock February 4, 2025 07:17 by author Peter

Node Version Switcher, or NVS for short, is a cross-platform utility that may be used on Windows, Linux, and Mac workstations to manage several node versions on a single computer.

This program installs the various node versions in the Windows user profile folder without requiring administrator privileges on your workstation. Put otherwise, it won't interfere with the C:\Program Files or C:\System32 files.

Just like NVM (Node Version Manger)This tool manages all legacy and newer node versions independently and manages the runtime for you on the fly. As you see in the above screenshot, NVS can maintain multiple versions of node in same environment. Each version of the node can have its own tools and runtime.

The node is required for building SPFx (SharePoint Framework) solutions and building SPA (Single Page Applications) and many more.

Steps

Please follow the below steps to set up and configure NVS on windows workstation. Please note that all the steps are performed against windows 11 OS workstation
Step 1. Let us check if the workstation has NVS (Node Version Switcher) already installed.

Step 2. Let us try installing NVS on windows machine. In Windows 11, winget is already installed as part of OS and MSFT recommends using winget to install and maintain the software from Github repository. At first it is required to open the command prompt as administrator.

Step 3. in the CMD window, try running the below command to install the NVS. winget install jasongin.nvs –source winget

Step 4. Wait for the operation to complete. At the end you should be getting the message ‘Successfully installed’


Step 5. Close the command window. Open the command window again in ‘Administrator Mode’. This is required. Once opened type in ‘nvs’ in the command window. This time if you can see the nvs version numbers you are good and proceed to step 8. Else if you are getting the ‘Self signed certificate issue’ as per below screen capture then proceed to step 6.

Step 6. Copy the URL https://nodejs.org/dist/index.json in the chrome browser and download the certificate. Make sure you download file contains certificate chain. Click on the certificate information in browser.

Click on lock that says, ‘Connection is secure’.

Click on ‘Certificate is valid’

Click on the ‘Details’ tab.

Click on ‘Export Certificate’.

Step 7. Set up the environment variable for your profile under windows environment variables. Set the file for the environment variable to the certificate that you just downloaded.

Step 8. Open the command prompt as administrator and then type nvs and look for the below output.

Step 9. If you do not have any version installed, you will be asked to select the node versions from the available binaries. In this case I have chosen to install the version 18.20.6 by using the below command.

nvs add 10.20.6

Step 10. Once the installation starts you will be getting below message.

After couple of minutes, you should get a message that the specified node version is added.

Step 11. clear the screen and type I nvs, you should get the versions now. Select the required version.


Step 12: I have type in (a). you can select the one that is required for your needs. Once selected you can check the version by using the below command.

node –v

Conclusion
Thus, in this article, you have seen how to install NVS a cross-platform tool to manage multiple node versions efficiently, in windows workstation.

HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Node.js Hosting Europe - HostForLIFE.eu :: How To Creating a Live Chat App Using Socket.IO and Node.js?

clock January 16, 2025 07:48 by author Peter

A fundamental element of modern web development is the usage of live chat software to enable real-time user contact. Using technologies like Socket.IO and Node.js greatly simplifies the process. Socket.IO is a JavaScript library that allows bidirectional, real-time communication between web clients and servers, resulting in stable connections across all browsers. Node.js, a stable runtime environment that uses an event-driven, non-blocking I/O model, makes it simple to create scalable network applications.

Steps for Creating a Project]
Step 1. Setting Up the Project
Use my previous article for setting up Node.js, "How to upload file in Node.js" In this article, we mentioned important commands for uploading files in Node.js.

Step 2. Setting Up the Server
Create the Server File. Create a file named index.js
const express = require('express');
const app = express();
const { Server } = require('socket.io');
const http = require('http');
const server = http.createServer(app);
const io = new Server(server);
const port = 4000;
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
    socket.on('send name', (username) => {
        io.emit('send name', username);
    });
    socket.on('send message', (chat) => {
        io.emit('send message', chat);
    });
});
server.listen(port, () => {
    console.log(`Server is listening at the port: ${port}`);
});

Step 3. Creating the Frontend

Create the HTML File. Create a file named index.html
<!DOCTYPE html>
<html>
<head>
    <title>Chat app using Socket IO and Node JS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        h1 {
            color: #273c75;
        }

        .msg-box {
            display: flex;
            flex-direction: column;
            background: darkgray;
            padding: 20px;
        }
    </style>
</head>
<body>
    <h1 class="font-bold text-3xl text-center mt-5">
        C# Corner Chat App using Socket IO and Node JS
    </h1>
    <div>
    </div>
    <form class="flex flex-col justify-center items-center mt-5" id="form">
        <div class="msg-box">
            <input class="border border-gray-400 rounded-md mt-5 p-1" type="text" placeholder="Name" id="myname"
                autocomplete="off">
            <input class="border border-gray-400 rounded-md mt-5 p-1" type="text" placeholder="Message" id="message"
                autocomplete="off">
            <button class="bg-blue-500 rounded-md p-2 text-white mt-5">
                Send
            </button>
        </div>
    </form>
    <div class="flex flex-col justify-center items-center mt-5" id="messageArea">
    </div>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
    let socket = io();
    let form = document.getElementById('form');
    let myname = document.getElementById('myname');
    let message = document.getElementById('message');
    let messageArea = document.getElementById("messageArea");
    form.addEventListener("submit", (e) => {
        e.preventDefault();
        if (message.value) {
            socket.emit('send name', myname.value);
            socket.emit('send message', message.value);
            message.value = "";
        }
    });
    socket.on("send name", (username) => {
        let name = document.createElement("p");
        name.style.backgroundColor = "#a59494";
        name.style.textAlign = "center";
        name.style.color = "white";
        name.textContent = username + ":";
        messageArea.appendChild(name);
    });
    socket.on("send message", (chat) => {
        let chatContent = document.createElement("p");
        chatContent.textContent = chat;
        messageArea.appendChild(chatContent);
    });
</script>
</html>

Step 4. Running the Application
Run the command in CMD.
node index.js

In the output, you can open the chat application in two different browsers or different tabs. When you start typing and send a message, it reflects on both screens in real-time.

Conclusion

You have now successfully used Node.js and Socket.IO to develop a basic live chat application. This application facilitates real-time communication between users by rapidly reflecting messages across several linked clients. To make your app even better, think about including features like private messaging, user authentication, and database storage for conversation history. Using CSS frameworks or original designs to enhance the user interface can improve the user experience. Use Vercel or Heroku to launch your application for increased accessibility. Continue researching and experimenting to create a robust and feature-rich chat experience. Enjoy yourself while coding!



Node.js Hosting Europe - HostForLIFE.eu :: How to Create a Node.js Logging System with Express?

clock April 25, 2024 13:50 by author Peter

In contemporary web development, logging plays a crucial role in program monitoring and troubleshooting. Node.js offers a variety of logging tools for monitoring and analyzing application operations because of its event-driven architecture. This article will walk through how to build a logging system for a Node.js application using Winston, a versatile logging package, and Express, a popular web framework.

What is Logging?
The process of keeping track of activities and occurrences inside a software system is called logging. These log entries help with debugging, monitoring, auditing, and security. They include timestamps, severity levels, messages, and contextual data. Logging helps with performance analysis, intrusion detection, compliance adherence, and troubleshooting by capturing important information about system behavior. With their ability to provide insights into application flow, performance bottlenecks, user actions, and security concerns, logs are an indispensable tool for developers, administrators, and security professionals. Logging is essentially a basic procedure used in software development and operations that makes software systems easier to manage, secure, and monitor.

Why we use Logging?

Logging serves several essential purposes in software development:

  • Debugging and Troubleshooting: Logs are an important source of information for troubleshooting and identifying difficulties with a program. To comprehend the execution flow, spot faults, and find the source of problems, developers can go through log messages.
  • Monitoring and Performance Optimization: Developers may keep an eye on an application's performance in real time with the help of logs. Developers can pinpoint performance bottlenecks, maximize resource use, and raise the application's general effectiveness by examining log data.
  • Auditing and Compliance: Keeping track of user actions and system events is facilitated by logging. For compliance with legal standards like GDPR, HIPAA, or PCI DSS, this audit trail is crucial. Logs are useful for monitoring user behavior, spotting illegal access, and guaranteeing the accuracy of data.
  • Security and Intrusion Detection: When it comes to identifying security risks and unauthorized access attempts, logs are essential. Events including unsuccessful login attempts, questionable activity, and possible security breaches are recorded in security logs. Administrators are able to quickly identify and address security incidents by examining security logs.

Steps for Creating a Project
Step 1.  Setting Up the Project
Use my previous article for setting up Node.js, "How to upload file in Node.js" In this article, we mentioned important commands for uploading files in Node.js.

Step 2. Integrating Winston for Logging

Winston is a versatile Node.js logging package that supports many transports, such as file, database, and terminal. Winston will be set up to log messages to both the console and a log file at various levels (info, error, etc.).
// main.js

const winston = require('winston');

// Create a logger instance
const logger = winston.createLogger({
  level: 'info', // Logging level
  format: winston.format.json(), // Log format
  transports: [
    // Log to the console
    new winston.transports.Console(),
    // Log to a file
    new winston.transports.File({ filename: 'logging_file.log' })
  ]
});


Step 3.  Implementing Logging Middleware in Express
We are able to intercept and handle incoming requests thanks to express middleware. A unique middleware function will be developed to log incoming HTTP requests. Request methods, URLs, and other pertinent data will be recorded by this middleware and logged using Winston.
// Middleware to log requests
app.use((req, res, next) => {
  logger.log('info', `${req.method} ${req.url}`);
  next();
});

Step 4.  Creating Routes and Handling Errors
After installing logging middleware, we will create our Express application's routes. To show how to handle requests, we'll construct a simple route for the main page ("/"). Furthermore, error handling middleware will be implemented to log and manage any faults that arise during request processing.
// Route handling
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

// Error handling middleware
app.use((err, req, res, next) => {
  logger.log('error', err.stack);
  res.status(500).send('Something broke!');
});


Step 5. Serving Log File via Web Interface
We'll develop an additional route ("/logs") that reads the contents of the log file and sends it to the client in order to give a user-friendly way for log files to be viewed. In order to ensure security and avoid dangerous infinite loops, this route will ignore logging requests so they are not kept in the log file.
// Route to serve log file
app.get('/logs', (req, res) => {
  fs.readFile('combined.log', 'utf8', (err, data) => {
    if (err) {
      logger.log('error', err);
      return res.status(500).send('Error reading log file');
    }
    res.type('text/plain').send(data);
  });
});


Step 6. Running the Application

Finally, let us launch our Express application and verify its operation. To start the HTTP request logging, start the server and visit the home page. You may also view the contents of the log file using the web interface by going to the "/logs" route.
node main.js

Output



Node.js Hosting Europe - HostForLIFE.eu :: TODO application with CQRS Design Pattern within Nest JS

clock December 4, 2023 08:53 by author Peter

A software design pattern called CQRS (Command Query Responsibility Segregation) divides up who is responsible for accessing and writing data in a system. The same set of components are frequently used in traditional design patterns for both reading and writing data. CQRS introduces two distinct models to suggest the division of these duties.

 

  • Command Model: The command model handles event triggering, data store updating, and command processing and validation.
  • Query Model: This model manages the processes involved in getting data out of the system.

The four major concepts of CQRS are listed below:

  • Command: Action or request to modify the system's status
  • Query: An occurrence or a request to obtain data from the system
  • Command Handler: An element in charge of processing commands and adjusting the system's state.
  • Query Handler: An element in charge of managing queries and getting information out of the system.

CQRS Offers Advantages like:

  • Scalability: Because the application supports several read and write data models, it can be scaled.
  • Flexibility: It permits the use of distinct data stores that are best suited for writing and reading processes.
  • Performance: There is room for improvement with this application.

This CQRS Model may be used with Nest JS; in this tutorial, we'll discover how to do it.

We'll use the creation and retrieval of a TODO application as an example using the CQRS paradigm.

Application for TODOs using CQRS pattern
You must use the command line to install nest cli if it is not already installed globally on your computer.
npm i -g @nestjs/cli

Create new Nest Js project if not created already using below command
nest new todo-application

Dependency Installation
Nest JS provides a package to implement CQRS, we need to install the package first using below command
npm install --save @nestjs/cqrs

Module Creation
Create new Module for our TODO application using command
nest generate module todo

Commands
Commands are used to change the application state, when a command is triggered, it is handled by corresponding command handler. Then handler will be responsible to process the operation. Every command will have command handler in order to process the command

Create new file inside todo module with name create-todo-command.ts and implement the below code
import { ICommand } from '@nestjs/cqrs';

export class CreateToDoCommand implements ICommand {
    constructor(
      public readonly title: string,
      public readonly description: string,
    ) {}
}

Command Handler
Create new file inside todo module with name create-todo-command-handler.ts  and implement the below code

import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { CreateToDoCommand } from './create-todo-command';

@CommandHandler(CreateToDoCommand)
export class CreateToDoHandler implements ICommandHandler<CreateToDoCommand> {
  async execute(command: CreateToDoCommand): Promise<void> {
    // Add Logic to do validation and business rule
    const { title, description } = command;

    // Use Repository to save directly or Create Factory to add business logic and save
  }
}


Query
Queries are used to retrieve the data from the application, when a query is requested, Query handler handles the requests and retrieves the data. Every query will have query handler

Create new file inside todo module with name get-todo-query.ts  and implement the below code
import {  IQuery } from '@nestjs/cqrs';

export class GetToDoQuery implements IQuery {
    constructor() {}
}

Query Handler
Create new file inside todo module with name get-todo-query-handler.ts  and implement the below code
import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { GetToDoQuery } from './get-todo-query';

@QueryHandler(GetToDoQuery)
export class GetToDoQueryHandler implements IQueryHandler<GetToDoQuery> {
  async execute(query: GetToDoQuery): Promise<any> {
    // Fetch data using repository or factory and return it
    // Sample Response
    return [
      { id: 1, title: 'Test', description: 'Reminder to complete daily activity' },
      { id: 2, title: 'Test 2', description: 'Reminder to complete daily activity2' },
    ];
  }
}


Module
In the todo.module.ts  file, import the CQRS module to use the command handlers and query handlers
import { Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { ToDoController } from './todo.controller';
import { CreateToDoHandler } from './create-todo-command-handler';
import { GetToDoQueryHandler } from './get-todo-query-handler';

@Module({
  imports: [CqrsModule],
  controllers: [ToDoController],
  providers: [CreateToDoHandler, GetToDoQueryHandler],
})
export class ToDoModule {}


Controller
Create todo.controller.ts  file to handle the API request and use command and query bus
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CommandBus, QueryBus } from '@nestjs/cqrs';
import { CreateToDoCommand } from './create-todo-command';
import { GetToDoQuery } from './get-todo-query';

@Controller('ToDo')
export class ToDoController {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly queryBus: QueryBus,
  ) {}

  @Post()
  async createToDo(@Body() body: { title: string, description: string }): Promise<void> {
    const { title, description } = body;
    await this.commandBus.execute(new CreateToDoCommand(title, description));
  }

  @Get()
  async getToDo(): Promise<any[]> {
    return this.queryBus.execute(new GetToDoQuery());
  }
}

Pro Tips
You can create a separate folder for command and query to segregate the code and make it more readable. Also, here I just gave the basic high level demo, but in your application, you can create dto for command and query, and you can directly use that dto
Conclusion

In conclusion, while CQRS can provide advantages in terms of scalability and flexibility, it comes with increased complexity and potential challenges in terms of consistency and development overhead. It is important to carefully consider whether the benefits align with the specific requirements and goals of the application being developed.

HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.




Node.js Hosting Europe - HostForLIFE.eu :: How to Choose PDF Library in Node.js?

clock October 13, 2023 09:54 by author Peter

When it comes to document sharing, Adobe's Portable Document Format (PDF) is critical for maintaining the integrity of text-rich and aesthetically pleasing data. Access to online PDF files often necessitates the use of a certain application. Many prominent digital publications now need PDF files. Many companies utilize PDF files to create expert documentation and invoices. Additionally, developers usually employ PDF document generating libraries to meet specific client requirements. The introduction of contemporary libraries has simplified the process of creating PDFs.

What exactly is Node.js?
Node.js is a cross-platform, open-source server environment that works with Windows, Linux, Unix, macOS, and other operating systems. Node.js is a JavaScript back-end runtime environment that uses the V8 JavaScript engine to execute JavaScript code outside of a web browser.

Developers can utilize JavaScript to construct server-side scripts and command-line tools with Node.js. Dynamic web page content is commonly built before a page is sent to a user's web browser by utilizing the server's ability to run JavaScript code. Node.js promotes a "JavaScript everywhere" paradigm that unifies online application development around a single programming language, as opposed to using several languages for server-side and client-side programming.

const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.text('Hello world', 100, 100)
doc.end();
doc.pipe(fs.createWriteStream('Output.pdf'));


PDFmake

A wrapper library for PDFKit is called pdfmake . The programming paradigm is where there is the most difference:

While pdfmake uses a declarative approach, pdfkit uses the traditional imperative technique. Because of this, concentrating on what you want to perform is simpler than spending time instructing the library on how to get a particular outcome.

But not everything that glitters is gold, and using Webpack and trying to integrate bespoke fonts may cause problems. Unfortunately, there isn't much information regarding this problem available online. If you don't use Webpack, you can still easily clone the git repository and run the script for embedded font.

var fonts = {
  Roboto: {
    normal: 'fonts/Roboto-Regular.ttf',
    bold: 'fonts/Roboto-Medium.ttf',
    italics: 'fonts/Roboto-Italic.ttf',
    bolditalics: 'fonts/Roboto-MediumItalic.ttf'
  }
};

var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);
var fs = require('fs');

var docDefinition = {
  // ...
};

var options = {
  // ...
}

var pdfDoc = printer.createPdfKitDocument(docDefinition, options);
pdfDoc.pipe(fs.createWriteStream('output.pdf'));
pdfDoc.end();


jsPDF
Among the PDF libraries on GitHub, jsPDF is a PDF generation library for browsers. It has the most starts, and this is not a coincidence given how reliable and well-maintained it is. Because the modules are exported in accordance with the AMD module standard, using them with nodes and browsers is simple.

For PDFKit, the offered APIs follow an imperative paradigm, making it difficult to create complicated layouts. Including typefaces The only additional step is to convert the fonts to TTF files, which is not difficult. Although jsPDF is not the simplest library to use, the extensive documentation ensures that you won't run into any specific difficulties when using it.

import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("output.pdf");

Puppeteer
Puppeteer is a Node library that offers a high-level API to manage Chrome, as you may know, but it can also be used to as PDF generator. Because the templates must be written in HTML, jsPDF is fairly simple for web developers to use.

Puppeteer has mostly two drawbacks. You must put a backend solution in place. Puppeteer must be launched each time a PDF needs to be created, adding to the burden. It moves slowly.

It might be an excellent solution if the aforementioned drawbacks are not a major issue for you, especially if you need to construct HTML tables and other such things.
const puppeteer = require('puppeteer')

async function printPDF() {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto('www.google.com', {waitUntil: 'networkidle0'});
  const pdf = await page.pdf({ format: 'A4' });
  await browser.close();
  return pdf
})


While pdfmake is based on PDFKit, pdf-lib is a library for producing and editing PDFs that is entirely written in Typescript. Even though it was launched after all the other libraries, it has thousands of stars on GitHub, indicating how well-liked it is.

The APIs have a fantastic design and naturally function with both browsers and nodes.It offers many features that other libraries simply don't have, including PDF merging, splitting, and embedding;

Although it is quite powerful, pdf-lib is also very user-friendly. One of the most popular features is the ability to embed font files using Unit8Array and ArrayBuffer, which enables using fs while dealing with nodes and xhr when working in the browser.

When you compare it to other libraries, you'll be able to tell that it performs better, and you can utilize Webpack with it, of course. Additionally, this library uses an imperative approach, which makes it difficult to work with complex layouts.
import { PDFDocument } from 'pdf-lib'

// PDF Create
const pdfDoc = await PDFDocument.create()
const page = pdfDoc.addPage()
page.drawText('Hello World')
const pdfBytes = await pdfDoc.save()

IronPDF
IronPDF for Node.js renders PDFs from HTML strings, files, and web URLs by using the robust Chrome Engine. It is advised to assign this operation to the server side since rendering can be computationally demanding. In order to offload the computational effort and await the outcome, frontend frameworks like ReactJs and Angular can communicate with the server. The outcome can then be shown on the front end side.

Software engineers may produce, modify PDF documents, and extract PDF material with the use of the IronPDF library, which was created and maintained by Iron Software.

When it comes to
    the creation of PDF documents using HTML, URL, JavaScript, CSS, and a variety of image formats
    A signature and headers should be included.
    Add, Copy, Split, Merge, and Delete PDF Pages
    Can able to include CSS properties.
    Performance improvement Async and complete multithreading support

import {PdfDocument} from "@ironsoftware/ironpdf";

(async () => {
  const pdf = await PdfDocument.fromHtml("<h1>Hello World</h1>");
  await pdf.saveAs("Output.pdf");
})();




Node.js Hosting Europe - HostForLIFE.eu :: npm vs yarn vs pnpm

clock September 20, 2023 08:39 by author Peter

Let's look at the differences between npm, yarn, and pnpm in this blog. Package managers such as npm, yarn, and pnpm are extensively used in the JavaScript ecosystem to manage dependencies and packages for Node.js projects. They take different approaches and have distinct features, which can affect how they manage packages and interact with your project.

npm

npm is the default package manager for Node.js and is included with the installation of Node.js. It has a lengthy history and is frequently used in the JavaScript ecosystem. To store and distribute packages, npm makes use of a centralized package registry known as the npm registry. It adds a "node_modules" directory to your project and installs all project dependencies there.

// Install a package
npm install package-name

//Update a package
npm update package-name

// Remove a package
npm uninstall package-name


yarn

// Install a package
yarn add package-name

// update a package
yarn upgrade package-name

// Remove a package
yarn remove package-name


pnpm

pnpm is another package manager for Node.js projects. It aims to solve the issue of disk space usage by using a unique approach. Instead of creating a separate "node_modules" directory for each project, pnpm uses a single global package store and creates symlinks to the required packages in each project's "node_modules" directory. This can significantly reduce the amount of disk space used by your projects.

// Install a package
pnpm add package-name

// update a package
pnpm update package-name

//Remove a package
pnpm remove package-name


HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.




Node.js Hosting Europe - HostForLIFE.eu :: Using Immer to Navigate State Management in JavaScript

clock September 6, 2023 09:48 by author Peter

Wrangling application state is a vital skill in the dynamic arena of web development. Keeping code tidy and predictable can be difficult, but the introduction of tools like Immer has provided a breath of fresh air in this sector. Immer has won the hearts of developers all over the world with its ease of use and efficiency in dealing with state changes. This essay will take you on a journey into the world of Immer, looking into its practical implementation, benefits, and how it makes the sometimes difficult chore of state management in JavaScript a lot easier.

Immer, lovingly created by Michel Weststrate, is a library that changes the way we deal with data immutability. It enables us to write code that appears to modify state directly while actually orchestrating the construction of new, immutable state structures.1. Starting Out: InstallationLet's begin your Immer trip by installing the library with npm or yarn.
npm install immer

2. Basic Usage
At the core of Immer is a function called produce. It's the magic wand that takes your current state and a function containing your desired changes and works its enchantment.

import produce from 'immer';

const initialState = { count: 0 };

const nextState = produce(initialState, draftState => {
  draftState.count += 1;
});


3. Taming Nesting
Now comes the pièce de résistance. Immer's prowess shines when dealing with deeply nested objects and arrays. It simplifies complex state structures with ease.
const complexState = {
  user: {
    name: 'Alice',
    address: {
      city: 'Wonderland'
    }
  }
};

const newState = produce(complexState, draftState => {
  draftState.user.name = 'Bob';
  draftState.user.address.city = 'Dreamland';
});


Benefits
    Crystal Clarity: Immer brings lucidity to your code. Instead of fretting about cloning and immutability, you can focus on the changes you wish to make.
    Performance Star: The magic of Immer not only simplifies your code but optimizes performance by reducing memory overhead and avoiding redundant copying.
    Readable Harmony: Code created with Immer mirrors traditional mutable code, fostering understanding and maintainability.

Conclusion

Immer has reimagined the landscape of state management in JavaScript applications. Its knack for handling immutable updates effortlessly, coupled with an approachable syntax, is nothing short of revolutionary. By streamlining the intricate dance of cloning and immutability checks, Immer reduces error risks and transforms the development experience.

In the ever-evolving world of web development, where efficiency and maintainability are paramount, Immer emerges as a steadfast ally. Whether you're working on a modest project or an intricate application, incorporating Immer into your state management arsenal offers cleaner, bug-free code and boosts developer productivity.

So, as you embark on your coding escapades, remember that Immer isn't just a library; it's a compass that guides you through the labyrinth of state management, making your journey more delightful and your code more enchanting.



Node.js Hosting Europe - HostForLIFE.eu :: How Do I Use Multer to Upload Multiple Files in Node.js?

clock July 21, 2023 08:46 by author Peter

This post will teach you how to upload numerous files in Node.js. In Node.js, we upload files using many libraries. In this article, we discuss a really basic and simple method for beginners, complete with examples. There is also a "rar" file attached to export your system and execute it properly.


Steps for Starting a Project
Step 1: Create a Node.js Project

Use my previous article "How to Upload File in Node.js" for Node.js setup. In this article, we discussed crucial Node.js commands for uploading files.

Step 2: Project Organization.
When step one is finished, it produces some directories such as node modules, package-lock.json, and package.json, but we still need to build some files listed below the image. When the project is executed, the 'upload' folder is automatically created, and all uploaded files are saved to the 'upload' folder.

In this file structure, node_modules, package-lock.json, and package.json these files is created while you set up a project. We created index.js and views folder. Below attached all files used in this project.

Step 3. Create an index.js file.
In this file, have the "/" route and other necessary code required to run the project below the file is attached.

index.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const { render } = require('ejs');
var fs = require("fs");
const multer = require('multer');
const app = express();

// Middleware setup
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Set up static file serving for 'upload' folder
const uploadsPath = path.join(__dirname, 'upload');
app.use('/upload', express.static(uploadsPath));

// Route to render the 'first' view
/**
 * @route GET /
 * @description Render the 'first' view.
 */
app.get("/", function (req, res) {
    res.render('first');
});

// Set up multer storage and upload configuration
const storage1 = multer.diskStorage({
    destination: function (req, file, cb) {
        // Check the fieldname and store files accordingly
        if (file.fieldname === 'file1' || file.fieldname === 'file2' || file.fieldname === 'file3') {
            cb(null, path.join(__dirname, '/upload'));
        } else {
            cb(new Error('Invalid field name'));
        }
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname); // Use the original file name
    }
});
const uploadd = multer({ storage: storage1 });

// Configure multer fields for file uploads
/**
 * @typedef {Object} MulterField
 * @property {string} name - The name of the field for file upload.
 * @property {number} maxCount - The maximum number of files allowed to be uploaded for this field.
 */

/**
 * @type {MulterField[]} fields - Multer fields configuration for file uploads.
 */
const cpUpload = uploadd.fields([
    { name: 'file1', maxCount: 1 },
    { name: 'file2', maxCount: 8 },
    { name: 'file3', maxCount: 8 }
]);

// Route to handle file upload
/**
 * @route POST /fileupload
 * @description Handle file upload.
 * @returns {void}
 * @throws {Error} If an invalid field name is provided.
 */
app.post('/fileupload', cpUpload, (req, res) => {
    res.redirect('/');
});

// Start the server
/**
 * @description Start the server and listen on port 3001.
 * @event
 */
app.listen(3001, () => {
    console.log('server is running on port http://localhost:3001');
});

A server that can handle file uploads is created with the Node.js Express code that is provided. Multer, a well-known middleware library, is used to control file uploads. To render views, EJS is used as the templating engine. For the fields with the names "file1," "file2," and "file3," the application accepts file uploads. The 'upload' folder on the server is where the uploaded files are kept. Other developers will find it simpler to comprehend the functions of various routes and middlewares thanks to the inclusion of JSDoc comments in the code documentation. The 'first' view is rendered by the server at the root route, which operates on port 3001. When a file is successfully uploaded, the server returns users to the home page.

Step 4. Create first.ejs file.
This file has simple HTML and CSS code.

first.ejs
<!DOCTYPE html>
<html>
<head>
  <title>File Upload</title>
  <style>
    /* CSS styles for the file upload form */

    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
    }

    .container {
      max-width: 400px;
      margin: 0 auto;
    }

    .form-group {
      margin-bottom: 20px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }

    input[type="file"] {
      padding: 5px;
      border: 1px solid #ccc;
      border-radius: 4px;
      width: 100%;
    }

    input[type="submit"] {
      background-color: #4CAF50;
      color: white;
      padding: 10px 15px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    input[type="submit"]:hover {
      background-color: #45a049;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>File Upload</h2>
    <!-- File upload form -->
    <form action="/fileupload" method="post" enctype="multipart/form-data">
      <!-- File 1 input -->
      <div class="form-group">
        <label for="file1">File 1:</label>
        <input type="file" id="file1" name="file1">
      </div>
      <!-- File 2 input -->
      <div class="form-group">
        <label for="file2">File 2:</label>
        <input type="file" id="file2" name="file2">
      </div>
      <!-- File 3 input -->
      <div class="form-group">
        <label for="file3">File 3:</label>
        <input type="file" id="file3" name="file3">
      </div>
      <!-- Upload button -->
      <input type="submit" value="Upload">
    </form>
  </div>
</body>
</html>


Explanation

Three file input fields are created in a file upload form using the specified HTML code. Users can upload files by choosing them and submitting the form. The form gains visual components thanks to the CSS styles. The chosen files are sent to the "/fileupload" endpoint using the "post" method and "multipart/form-data" encoding when the form is submitted. The uploaded files are processed by the server, which manages the endpoint. Developers can better understand and manage the functioning of the form by using the HTML comments, which offer succinct explanations of the code's function and organization.

Output

 

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in