Full Trust European Hosting

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

Examining Node.js Applications Following the Most Recent HTTP/2 Security Updates

clock November 18, 2026 14:17 by author Peter

Node.js applications frequently employ HTTP/2 because it lowers protocol overhead, enhances client-server communication, and enables many requests to share a connection.
The implementation of HTTP/2 is more difficult than that of HTTP/1.1 due to the same protocol characteristics that make it beneficial. When an application gets traffic from untrusted clients, issues with connection handling, stream management, request processing, and resource restrictions may become security issues.

When a Node.js HTTP/2 security update becomes available, updating the Node.js runtime is only part of the work. Teams also need to check whether their applications are using the affected HTTP/2 functionality and whether the application configuration allows clients to consume excessive resources.

This article explains how to review a Node.js application after an HTTP/2 security fix, what areas should be checked, and how to test the application without changing unrelated parts of the system.

Why HTTP/2 Security Issues Need Application Review

A security fix in Node.js may address a problem inside the HTTP/2 implementation itself.
That means the vulnerable behavior may exist below your application code.

For example:
Client
   |
   v
Node.js HTTP/2
   |
   v
Application
   |
   v
Business Logic


If the issue exists in the HTTP/2 layer, the application may be vulnerable even when its own JavaScript code looks correct.

This is why reviewing the runtime version is important.

However, runtime version checking alone does not answer other important questions:

  • Is the application actually using HTTP/2?
  • Is HTTP/2 enabled directly or through a proxy?
  • Which server APIs are being used?
  • Are connection limits configured?
  • Are long-lived streams expected?
  • Is a reverse proxy involved?
  • Are HTTP/2 clients exposed directly to the application?

These questions help determine the practical impact of the security update.

Start by Checking the Node.js Version
The first step is to identify the runtime used by the application.

Run:
node --version

You can also check the version used in the project configuration.

For example:
{
  "engines": {
    "node": ">=22"
  }
}


The actual version requirement should match the supported runtime for your application and deployment platform.

Do not rely only on the Node.js version installed on your development machine.

Check the runtime used by:

  1. Local development
  2. CI/CD
  3. Docker images
  4. Virtual machines
  5. Kubernetes workloads
  6. Azure App Service
  7. Azure Container Apps
  8. Other hosting platforms

It is common for a developer's machine to run a newer Node.js version while production is still using an older runtime.

Check Where HTTP/2 Is Enabled

Search the application for HTTP/2 usage.

Common Node.js code includes:
const http2 = require("node:http2");

or:

import http2 from "node:http2";

A server may be created with:

const server = http2.createSecureServer({
    key,
    cert
});

If you find code like this, the application is directly using Node.js HTTP/2 APIs.
But the absence of this code does not necessarily mean the application never uses HTTP/2.

A reverse proxy may terminate HTTP/2 before forwarding HTTP/1.1 traffic to Node.js.

For example:
Client
   |
   | HTTP/2
   v
Reverse Proxy
   |
   | HTTP/1.1
   v
Node.js


In this setup, the Node.js application may not directly handle HTTP/2.

The reverse proxy becomes the component that needs to be reviewed for HTTP/2 security behavior.
Check the Entire Request Path

Modern applications often have several layers between the client and Node.js.

For example:
Internet
   |
   v
CDN
   |
   v
Load Balancer
   |
   v
Reverse Proxy
   |
   v
Node.js


A security review should identify which layer terminates the HTTP/2 connection.

This matters because the vulnerable protocol implementation may be located in a different component than the application server.

Ask these questions:

  • Does the public endpoint support HTTP/2?
  • Where is TLS terminated?
  • Does the Node.js process receive HTTP/2 directly?
  • Does a proxy convert HTTP/2 to HTTP/1.1?
  • Which component controls HTTP/2 connection limits?
  • Which component receives untrusted HTTP/2 traffic?

The answers determine where remediation needs to happen.

Review Node.js HTTP/2 APIs

If the application uses the Node.js HTTP/2 module directly, review how it creates and manages sessions.

For example:
const server = http2.createSecureServer({
    key: fs.readFileSync("server.key"),
    cert: fs.readFileSync("server.crt")
});

server.on("stream", (stream, headers) => {
    stream.respond({
        ":status": 200,
        "content-type": "text/plain"
    });

    stream.end("Hello");
});


The important part is not whether this exact code is vulnerable.
The important part is that the application is handling HTTP/2 streams directly and should therefore be tested after the runtime security update.

Review:

  • HTTP/2 sessions
  • Streams
  • Request headers
  • Response headers
  • Stream lifecycle
  • Error handling
  • Connection limits
  • Long-lived streams
  • Server shutdown behavior

Understand HTTP/2 Streams
HTTP/2 uses streams to allow multiple requests and responses over a single connection.

Conceptually:
One TCP connection
        |
        +-- Stream 1
        +-- Stream 2
        +-- Stream 3
        +-- Stream 4


This is efficient, but it also means an application needs to handle many concurrent streams correctly.

An application that assumes one connection equals one request can behave incorrectly under HTTP/2.

For example, application state should not be associated with the connection unless there is a clear reason to do so.

Request-specific information should remain associated with the request or stream.

Avoid Shared Mutable State

HTTP/2 makes concurrency especially important.

Suppose a server stores the current request in a global variable:
let currentRequest;

Then:
server.on("stream", (stream, headers) => {
    currentRequest = headers;

    // Process request
});

This is unsafe because multiple streams can exist at the same time.

A safer approach is to keep request data inside the stream handler:
server.on("stream", (stream, headers) => {
    const requestHeaders = headers;

    // Process this stream using requestHeaders
});


The same principle applies to normal Node.js applications.

HTTP/2 does not make shared mutable state safe.

Check Request Header Handling
HTTP/2 allows many headers to be sent with a request.

Applications should avoid making assumptions about the number or size of headers.

For example, code like this:
const userAgent = headers["user-agent"];

is fine when the application only needs that specific header.

Problems can appear when the application copies every header into another object, logs everything, or performs expensive processing without limits.

Review:

  • Header validation
  • Header logging
  • Header size assumptions
  • Duplicate or unexpected headers
  • Sensitive headers
  • Authentication headers

Never log complete authorization headers or other secrets simply for troubleshooting.

Review Long-Lived Connections

Some applications intentionally keep HTTP/2 connections alive for long periods.
This can be normal for certain workloads, but it means connection management becomes important.

Review:

  • Connection idle timeouts
  • Stream timeouts
  • Maximum concurrent streams
  • Graceful shutdown
  • Connection cleanup
  • Error handling

Do not simply reduce all timeout values without understanding the application's traffic pattern.
A streaming application may legitimately need longer-lived connections than a typical REST API.
The goal is controlled resource usage, not arbitrary timeout reduction.

Check Reverse Proxy Configuration

If Node.js sits behind a reverse proxy, inspect the proxy configuration as well.

A common architecture is:
Client
   |
   | HTTP/2
   v
Proxy
   |
   | HTTP/1.1
   v
Node.js


In this architecture, the Node.js application may not be responsible for HTTP/2 negotiation.
The proxy handles the HTTP/2 connection.

Review:

  • HTTP/2 enablement
  • Connection limits
  • Request limits
  • Stream limits
  • TLS configuration
  • Timeout configuration
  • Header forwarding
  • Proxy upgrade behavior

Do not assume that upgrading Node.js alone fixes every HTTP/2 security exposure in the environment.

Check Docker Images

Containerized applications can easily run an unexpected Node.js version.

A Dockerfile might contain:
FROM node:22

WORKDIR /app

COPY package*.json ./

RUN npm ci

COPY . .

CMD ["node", "server.js"]


The important question is which exact image version is actually being deployed.
Using a broad tag can make runtime behavior change when the image is rebuilt.
For production applications, consider using a controlled base image strategy and update it deliberately through the normal dependency and security process.

After updating the image, verify the runtime:
node --version

inside the container.

Check CI/CD Pipelines

The runtime used by CI can also differ from production.

For example, a GitHub Actions workflow might use:
steps:
  - uses: actions/checkout@v4

  - uses: actions/setup-node@v4
    with:
      node-version: 22

  - run: npm ci
  - run: npm test

This only tells you what version is used during CI.

Your production deployment could still use another version.

Check the complete pipeline:
Source Code
    ↓
CI Node.js Version
    ↓
Build Artifact
    ↓
Container / Server Runtime
    ↓
Production

The runtime used for the final application matters most.

Review package-lock.json

Updating Node.js does not necessarily mean updating every npm dependency.
Do not use a security update as an excuse to upgrade unrelated packages without a reason.
Start by identifying the runtime issue and its affected components.

Then review dependencies separately.

Useful commands include:
npm outdated

and:
npm audit

The output from npm audit should be reviewed rather than blindly applying every suggested upgrade.
A dependency update can introduce a different application problem.

Keep the scope of the security fix controlled.

Test HTTP/1.1 and HTTP/2 Separately
After updating Node.js, test both protocols when the application supports both.

For example:
curl --http1.1 https://example.com/

and:
curl --http2 https://example.com/
This helps identify protocol-specific behavior.


If HTTP/1.1 works but HTTP/2 fails, investigate the HTTP/2 path rather than changing application logic that is unrelated to the protocol.

Test With a Realistic Load
A security fix may change how the runtime handles malformed or unusual HTTP/2 traffic.
Normal functional tests are important, but they may not exercise connection behavior under load.
Test scenarios such as:

  • Multiple concurrent clients
  • Multiple streams per connection
  • Long-running requests
  • Slow clients
  • Large request headers
  • Connection reuse
  • Repeated connection creation

The goal is to confirm that the application remains stable after the runtime update.
Do not generate intentionally malicious traffic against a production system.
Use a controlled test environment for security and protocol stress testing.

Watch CPU and Memory Usage

After deploying the updated runtime, monitor resource usage.

Important metrics include:

  • CPU
  • Memory
  • Request rate
  • Request duration
  • Active connections
  • Error rate
  • Restart count
  • Container health

A runtime update may change behavior under certain traffic patterns.

Compare the application before and after the deployment.

For example:
Before update
CPU: stable
Memory: stable
Errors: low

After update
CPU: stable
Memory: stable
Errors: low


If memory usage starts increasing after deployment, investigate before assuming the HTTP/2 fix itself caused the problem.

Watch for Connection and Stream Errors

Application logs may contain errors related to:
ERR_HTTP2_PROTOCOL_ERROR
ERR_HTTP2_STREAM_ERROR
ERR_HTTP2_INVALID_SESSION

The exact error depends on the runtime and application behavior.

Do not treat every HTTP/2 error as a security issue.

First determine whether the error is:

  • Client-generated
  • Proxy-generated
  • Application-generated
  • Runtime-generated
  • Caused by a network interruption

Look at the complete request path.

Review Graceful Shutdown

A production Node.js server should handle shutdown correctly.

For example:
const server = http2.createSecureServer(options);

process.on("SIGTERM", () => {
    server.close(() => {
        process.exit(0);
    });
});


The exact shutdown behavior depends on the application's architecture.
The important point is that HTTP/2 connections may remain active during shutdown.
The application should stop accepting new work while allowing existing operations to finish within the configured limits.
This becomes especially important when containers are replaced during a deployment.

Do Not Disable HTTP/2 Without a Reason

One possible reaction to an HTTP/2 security issue is to disable HTTP/2 completely.

That may reduce exposure, but it can also remove features the application depends on.

Before disabling HTTP/2, determine:

  • Whether the application uses it
  • Whether the public endpoint requires it
  • Whether the reverse proxy handles it
  • Whether clients depend on it
  • Whether the security update is already available

If a supported Node.js security update fixes the issue, upgrading the runtime is generally preferable to removing a protocol feature unnecessarily.

Test Streaming Applications Carefully

Some Node.js applications use HTTP/2 streaming.

For example:
server.on("stream", (stream, headers) => {
    stream.respond({
        ":status": 200,
        "content-type": "text/event-stream"
    });

    const interval = setInterval(() => {
        stream.write("data: update\n\n");
    }, 1000);

    stream.on("close", () => {
        clearInterval(interval);
    });
});


Streaming changes the testing requirements.

Check:

  • Client disconnect handling
  • Stream cleanup
  • Timer cleanup
  • Memory usage
  • Connection duration
  • Graceful shutdown

A stream that is not cleaned up properly can continue consuming resources after the client has gone away.



AngularJS Hosting Europe - HostForLIFE :: How to Handle Form Validation in Angular with Reactive Forms?

clock November 16, 2026 14:58 by author Peter

Reactive Forms in Angular give you strong, predictable, and testable ways to build forms and validate user input. Unlike template-driven forms, reactive forms are defined and managed in your component TypeScript code using FormGroup, FormControl, and FormBuilder. This makes them ideal for complex validation rules, dynamic forms, and large applications used by developers.

Create a Basic Reactive Form
Start by importing ReactiveFormsModule in your Angular module:
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [ReactiveFormsModule, /* other imports */],
})
export class AppModule {}

Then, build a form in your component using FormBuilder:

// user-form.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({ selector: 'app-user-form', templateUrl: './user-form.component.html' })
export class UserFormComponent {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]],
    });
  }
}


In the template, bind the form and controls:
<!-- user-form.component.html -->
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <label>
    Name
    <input formControlName="name" />
  </label>
  <div *ngIf="userForm.get('name')?.touched && userForm.get('name')?.invalid">
    <small *ngIf="userForm.get('name')?.errors?.required">Name is required.</small>
    <small *ngIf="userForm.get('name')?.errors?.minlength">Name must be at least 2 characters.</small>
  </div>

  <label>
    Email
    <input formControlName="email" />
  </label>
  <div *ngIf="userForm.get('email')?.touched && userForm.get('email')?.invalid">
    <small *ngIf="userForm.get('email')?.errors?.required">Email is required.</small>
    <small *ngIf="userForm.get('email')?.errors?.email">Enter a valid email.</small>
  </div>

  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>

Built-in Validators
Angular provides several built-in validators:

  • Validators.required — field must have a value.
  • Validators.email — value must be a valid email.
  • Validators.min / Validators.max — numeric limits.
  • Validators.minLength / Validators.maxLength — string length limits.
  • Validators.pattern — regex-based validation.

You can combine validators in an array for a control, as shown in the example above.

Custom Synchronous Validators
For rules that don’t exist out of the box (e.g., username format), write a custom validator function that returns either null (valid) or an error object:
import { AbstractControl, ValidationErrors } from '@angular/forms';

export function usernameValidator(control: AbstractControl): ValidationErrors | null {
  const value = control.value as string;
  if (!value) return null;
  const valid = /^[a-z0-9_]+$/.test(value);
  return valid ? null : { invalidUsername: true };
}

// usage in form builder
this.userForm = this.fb.group({
  username: ['', [Validators.required, usernameValidator]],
});


Show helpful messages in the template when invalidUsername exists.

Cross-Field Validation (Password Match)

Some validations depend on multiple controls. Use a validator on the FormGroup:
function passwordMatchValidator(group: AbstractControl): ValidationErrors | null {
  const password = group.get('password')?.value;
  const confirm = group.get('confirmPassword')?.value;
  return password === confirm ? null : { passwordsMismatch: true };
}

this.userForm = this.fb.group({
  password: ['', Validators.required],
  confirmPassword: ['', Validators.required],
}, { validators: passwordMatchValidator });

In the template, show the group-level error:
<div *ngIf="userForm.errors?.passwordsMismatch && userForm.touched">
  <small>Passwords do not match.</small>
</div>


Async Validators (e.g., Check Email Uniqueness)
Async validators are useful for server checks like "is this email taken?". They return an Observable or Promise.
import { AbstractControl } from '@angular/forms';
import { map } from 'rxjs/operators';
import { of } from 'rxjs';

function uniqueEmailValidator(apiService: ApiService) {
  return (control: AbstractControl) => {
    if (!control.value) return of(null);
    return apiService.checkEmail(control.value).pipe(
      map(isTaken => (isTaken ? { emailTaken: true } : null))
    );
  };
}

// in component
this.userForm = this.fb.group({
  email: ['', {
    validators: [Validators.required, Validators.email],
    asyncValidators: [uniqueEmailValidator(this.apiService)],
    updateOn: 'blur' // run async validator on blur to reduce calls
  }]
});


Use updateOn: 'blur' to prevent calling the server on every keystroke.

Displaying Validation State and UX Tips

  • Show errors only after user interaction — use touched or dirty to avoid overwhelming users with errors on load.
  • Disable submit while invalid — [disabled]="userForm.invalid" prevents sending bad data.
  • Focus the first invalid control — on submit, set focus to the first invalid field for better UX.
  • Use updateOn: 'blur' or debounce — reduces validation frequency and server calls.

Example to focus first invalid:
onSubmit() {
  if (this.userForm.invalid) {
    const invalidControl = this.el.nativeElement.querySelector('.ng-invalid');
    invalidControl?.focus();
    return;
  }
  // process valid form
}

Reacting to Value Changes and Live Validation
You can subscribe to valueChanges for any control or the whole form to implement live validation messages, dynamic rules, or enable/disable fields.
this.userForm.get('country')?.valueChanges.subscribe(country => {
  if (country === 'US') {
    this.userForm.get('state')?.setValidators([Validators.required]);
  } else {
    this.userForm.get('state')?.clearValidators();
  }
  this.userForm.get('state')?.updateValueAndValidity();
});

Remember to unsubscribe in ngOnDestroy or use the takeUntil pattern.

Integrating with Backend Validation

Server-side validation is the final source of truth. When the backend returns validation errors, map them to form controls so users can correct them:
// after API error response
handleServerErrors(errors: Record<string, string[]>) {
  Object.keys(errors).forEach(field => {
    const control = this.userForm.get(field);
    if (control) {
      control.setErrors({ server: errors[field][0] });
    }
  });
}


Show control.errors.server messages in the template.

Testing Form Validation

Unit test reactive forms by creating the component, setting values, and asserting validity:
it('should invalidate empty email', () => {
  component.userForm.get('email')?.setValue('');
  expect(component.userForm.get('email')?.valid).toBeFalse();
});


For async validators, use fakeAsync and tick() to simulate time.

Accessibility (A11y) Considerations

  • Always link error messages to inputs with aria-describedby.
  • Use clear error language and avoid technical terms.
  • Ensure focus management sends keyboard users to errors on submit.

Example
<input id="email" formControlName="email" aria-describedby="emailError" />
<div id="emailError" *ngIf="userForm.get('email')?.invalid">
  <small>Enter a valid email address.</small>
</div>


Performance Tips and Best Practices

  • Use OnPush change detection where appropriate to reduce re-renders.
  • Avoid heavy computation inside valueChanges subscribers.

Use debounceTime for expensive validations or server calls:
this.userForm.get('search')?.valueChanges.pipe(debounceTime(300)).subscribe(...);

Clean up subscriptions with takeUntil or async pipe.

Summary
Reactive Forms in Angular offer a powerful, testable way to handle form validation. Use built-in validators for common rules, write custom sync and async validators for special cases, and place group validators for cross-field checks like password confirmation. Improve user experience by showing errors after interaction, focusing on the first invalid control, and integrating server-side errors with setErrors. Test your validations, keep accessibility in mind, and apply performance practices such as debouncing and OnPush change detection.



Node.js Hosting Europe - HostForLIFE.eu :: Why Node.js is Non-Blocking: Event Queue, Loop, and Emitters Explained?

clock November 12, 2026 14:15 by author Peter

Have you ever wondered how Node.js uses a single thread to manage thousands of users at once? Its non-blocking, event-driven architecture—powered by the event loop, event queue, and EventEmitter is the key. We'll examine how these elements interact to maintain Node.js's speed, low weight, and scalability in this post.

1. What Does "Non-Blocking" Mean?
In many traditional languages (like Java or Python), when you run a file read or an HTTP request, the program waits (blocks) until it's done.

But in Node.js, non-blocking means: "Do this task in the background, and when it's ready, I'll come back to it."This way, the main thread stays free to handle other tasks.

Example: Blocking vs Non-Blocking

Blocking Code
const fs = require('fs');
const data = fs.readFileSync('file.txt');  // Blocks here
console.log(data.toString());


Non-Blocking Code
const fs = require('fs');
fs.readFile('file.txt', (err, data) => {
  if (err) throw err;
  console.log(data.toString());  // Called when file is ready
});


In the second example, readFile doesn’t block. Instead, Node registers a callback and keeps moving. When the file is ready, the callback is run via the event loop.

2. Meet the Event Loop

The event loop is what allows Node.js to handle async operations without multiple threads.

How does it work?

  • Executes synchronous code first.
  • Checks if any callbacks are waiting in the event queue.
  • If yes, it picks one and runs it.
  • Repeats forever.

3. The Event Queue: Where Callbacks Wait
When an async task finishes (e.g., a timer or file read), the associated callback function goes into the event queue.

The event loop checks this queue, and if the call stack is clear, it runs the next callback.

Think of it like a task manager:

  • Tasks are scheduled
  • When resources are free, the task runs

4. Enter EventEmitter: Node’s Messaging System
Node.js comes with the EventEmitter class, which lets you create and respond to custom events. It's used internally in many core modules like http, fs, and stream.

Example
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('login', (user) => {
  console.log(`${user} just logged in!`);
});

emitter.emit('login', 'Alice');

    .on() listens for an event
    .emit() fires the event


5. Why This Design Makes Node.js So Powerful

  • Handles thousands of requests without threads
  • Never blocks the main thread on I/O
  • Scales easily on a single-core server
  • Great for real-time apps (chat, notifications, APIs)

Why Node.js Is Non-Blocking

Concept What It Does
Event Loop Runs continuously to check and execute tasks
Event Queue Stores completed async task callbacks
EventEmitter Custom event handling mechanism
Microtasks High-priority tasks like Promises
Macrotasks Timers, file I/O, etc.


Final Thoughts

Node.js isn't just fast-it's smart. Its ability to juggle async tasks using the event loop, event queue, and EventEmitter is what makes it non-blocking and perfect for modern web applications. Whether you're building a chat app, a REST API, or a streaming server, understanding how Node handles events under the hood will help you write better, faster, and more efficient code.



AngularJS Hosting Europe - HostForLIFE :: Building Authentication with JWT in Node.js

clock November 10, 2026 12:07 by author Peter

Authentication is a crucial part of any modern web application. Whether you're building a REST API, a SaaS product, or a mobile backend, you need a secure way to verify users. One of the most widely used approaches today is JWT (JSON Web Token) authentication. It allows you to securely transmit user identity between client and server in a stateless way. In this guide, we will implement JWT-based authentication using Node.js in a simple and practical way.

 

What is JWT?
JWT (JSON Web Token) is a compact, URL-safe token format used for authentication and authorization.

A JWT typically consists of three parts:

  • Header
  • Payload
  • Signature

Real-world analogy: Think of JWT like a digital ID card. Once issued, the client carries it and shows it to access protected resources.

Install Dependencies

First, install the required packages:
npm install express jsonwebtoken bcryptjs

Project Setup

Basic Express setup:
const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");

const app = express();
app.use(express.json());

const SECRET_KEY = "yourSecretKey";


Create JWT Token
This function generates a token when the user logs in successfully:
function generateToken(user) {
  return jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: "1h" });
}


Login Route
Here we validate user credentials and generate a token:
app.post("/login", async (req, res) => {
  const { email, password } = req.body;

  // Simulated user (in real apps, fetch from DB)
  const user = { id: 1, email, password: "123456" };

  if (password !== user.password) {
    return res.status(401).send("Invalid credentials");
  }

  const token = generateToken(user);
  res.json({ token });
});

Secure Password (Recommended Improvement)

Instead of storing plain passwords, use hashing:
const hashedPassword = await bcrypt.hash("123456", 10);
const isMatch = await bcrypt.compare(password, hashedPassword);


Middleware to Verify Token

This middleware protects routes by verifying JWT:
function authMiddleware(req, res, next) {
  const token = req.headers["authorization"];

  if (!token) return res.sendStatus(403);

  jwt.verify(token, SECRET_KEY, (err, decoded) => {
    if (err) return res.sendStatus(401);
    req.user = decoded;
    next();
  });
}


Protected Route Example

app.get("/profile", authMiddleware, (req, res) => {
  res.json({ message: "Protected data", user: req.user });
});


Step-by-Step Flow

  1. User logs in with email and password
  2. Server validates credentials
  3. Server generates JWT token
  4. Client stores token (localStorage or cookies)
  5. Client sends token in Authorization header
  6. Server verifies token before giving access

Real-World Example
Imagine a shopping app:

  • Without JWT: Server checks login every time (slow and heavy)
  • With JWT: User logs in once and reuses token for all requests (fast and scalable)

Advantages of JWT Authentication

  • Stateless (no session storage needed)
  • Scalable for large applications
  • Works well with APIs and microservices
  • Easy integration with frontend frameworks

Disadvantages

  • Token cannot be easily revoked (unless using blacklist)
  • Larger payload compared to session IDs
  • Requires careful handling of secret keys

Best Practices

  • Always store SECRET_KEY in environment variables
  • Use HTTPS to protect tokens
  • Set token expiration time
  • Use refresh tokens for long sessions
  • Avoid storing sensitive data in JWT payload

Conclusion
You now have a working JWT authentication system in Node.js. By combining Express, JWT, and secure password handling, you can build scalable and secure authentication for real-world applications. Start implementing this in your projects and gradually enhance it with refresh tokens, role-based access, and database integration.



AngularJS Hosting Europe - HostForLIFE :: Angular Signals: Preventing Unwanted Side Effects and Cleaning Up Effects

clock November 6, 2026 12:10 by author Peter

When data changes, Angular Signals offer a reactive method for managing state and updating application interfaces. Without depending solely on conventional change-detection techniques, they assist developers in clearly tracking dependencies, cutting down on pointless calculations, and creating components that react to state changes.

Reactive coding, however, presents unique difficulties. When an effect initiates a timer, registers an event listener, initiates a request, or subscribes to an external resource, it may go on even after the state that initiated it is no longer relevant.

For example, an Angular component might use an effect to start polling an API whenever a selected customer changes. If the previous polling operation is not stopped, multiple timers could remain active. These timers might issue unnecessary requests, consume resources, or update state using outdated results.

Angular provides cleanup mechanisms to help manage these situations. Understanding when an effect reruns, how onCleanup() works, and when to use DestroyRef or RxJS is essential for writing predictable reactive applications.

This article explains how Angular Signals effects work, how to clean up side effects correctly, and how to avoid common lifecycle and asynchronous programming problems.

Understanding Angular Signals
A signal is a reactive value that Angular can track when application code reads it. When the signal changes, Angular can notify the relevant consumers that depend on it.

Angular provides three important signal-related concepts:

  • signal() creates a writable signal.
  • computed() derives a value from other signals.
  • effect() runs code that reacts to signal dependencies.

Consider a component that tracks a selected product and its quantity:
import { Component, computed, signal } from '@angular/core';

@Component({
  selector: 'app-product-summary',
  standalone: true,
  template: `
    <h2>Product Summary</h2>

    <p>Quantity: {{ quantity() }}</p>
    <p>Total items: {{ totalItems() }}</p>

    <button (click)="increaseQuantity()">Add Item</button>
  `
})
export class ProductSummaryComponent {
  quantity = signal(1);
  itemsPerOrder = signal(3);

  totalItems = computed(
    () => this.quantity() * this.itemsPerOrder()
  );

  increaseQuantity(): void {
    this.quantity.update(value => value + 1);
  }
}

In this example, quantity and itemsPerOrder are writable signals. The totalItems computed signal derives its value from both.
When either dependency changes, Angular can recalculate the computed value when it is needed.
Notice that computed() is used for a derived value rather than an effect. This distinction matters because derived state should generally remain a computation, not an operation that introduces additional side effects.

What Is an Effect?

An effect runs a function that reads signals and performs an operation in response to changes in those signals.

For example:
import { Component, effect, signal } from '@angular/core';

@Component({
  selector: 'app-search-settings',
  standalone: true,
  template: `
    <button (click)="changeSearchTerm()">Change Search</button>
  `
})
export class SearchSettingsComponent {
  searchTerm = signal('Angular');

  constructor() {
    effect(() => {
      console.log('Current search term:', this.searchTerm());
    });
  }

  changeSearchTerm(): void {
    this.searchTerm.set('Angular Signals');
  }
}


The effect reads searchTerm(), so Angular tracks that signal as a dependency. When the signal changes, the effect can run again.

Effects are useful when reactive state must interact with an imperative API, such as browser storage, logging, or a third-party library.

They should not be the default mechanism for every reactive operation. For example, using computed() for derived state is generally clearer than using an effect to copy one signal's value into another.

Why Effect Cleanup Matters
An effect does not automatically know how to undo every operation performed by its callback.

Consider this example:
import { Component, effect, signal } from '@angular/core';

@Component({
  selector: 'app-polling',
  standalone: true,
  template: `
    <button (click)="changeCustomer()">Change Customer</button>
  `
})
export class PollingComponent {
  customerId = signal(1);

  constructor() {
    effect(() => {
      const customerId = this.customerId();

      setInterval(() => {
        console.log('Polling customer:', customerId);
      }, 5000);
    });
  }

  changeCustomer(): void {
    this.customerId.update(id => id + 1);
  }
}


This code contains a resource-management problem.
Every time customerId changes, the effect can execute again and create another interval. The previous interval continues running because nothing clears it.
After several customer changes, multiple timers may be active simultaneously.
The effect's reactive dependency tracking does not automatically clean up arbitrary resources created by its callback.
To handle this, Angular provides the onCleanup callback.

Using onCleanup() to Release Resources
Angular's effect callback can receive an onCleanup function. Registering a cleanup callback allows Angular to execute the cleanup before the effect runs again and when the effect is destroyed.

The general structure is:
effect((onCleanup) => {
  // Read signals and perform an operation.

  onCleanup(() => {
    // Release resources created by this effect run.
  });
});


The cleanup function should undo or release resources associated with that particular effect execution.

Fixing the Polling Example

The previous example can be corrected by clearing the interval:
import { Component, effect, signal } from '@angular/core';

@Component({
  selector: 'app-polling',
  standalone: true,
  template: `
    <button (click)="changeCustomer()">Change Customer</button>
  `
})
export class PollingComponent {
  customerId = signal(1);

  constructor() {
    effect((onCleanup) => {
      const customerId = this.customerId();

      const timerId = setInterval(() => {
        console.log('Polling customer:', customerId);
      }, 5000);

      onCleanup(() => {
        clearInterval(timerId);
      });
    });
  }

  changeCustomer(): void {
    this.customerId.update(id => id + 1);
  }
}

Now, when the effect reruns because customerId changes, Angular executes the cleanup associated with the previous run before proceeding with the new execution.
The previous interval is cleared, and the new run creates one interval for the selected customer.
When the effect is destroyed, Angular also runs its registered cleanup.
This prevents obsolete timers from continuing to execute.

Important Cleanup Rules
When using onCleanup(), follow these principles:

  • Register cleanup immediately after creating the resource whenever practical.
  • Capture the resource identifier or handle belonging to the current effect run.
  • Make sure cleanup releases only the resource owned by that run.
  • Do not assume cleanup runs every time a signal changes; it runs when the effect is scheduled to rerun and when the effect is destroyed.
  • Avoid placing unrelated application logic inside cleanup callbacks.

Cleanup should be predictable and limited to releasing resources, cancelling work, or restoring the state associated with the previous execution.

Cleaning Up Event Listeners

Event listeners are another common source of leaks in reactive applications.

Suppose an effect registers a browser event listener whenever a signal changes:
effect((onCleanup) => {
  const eventName = this.eventName();

  const handler = (event: Event) => {
    console.log(eventName, event.type);
  };

  window.addEventListener(eventName, handler);

  onCleanup(() => {
    window.removeEventListener(eventName, handler);
  });
});


The cleanup callback removes the exact listener created by that effect execution.

This detail is important because removeEventListener() must receive a matching event type, listener function, and compatible options.

Creating a new anonymous function inside the cleanup callback would not remove the original listener:
// Incorrect: this is a different function reference.
window.addEventListener('resize', () => {
  console.log('Window resized');
});

window.removeEventListener('resize', () => {
  console.log('Window resized');
});

The two arrow functions are different function objects. The removal operation therefore does not unregister the original listener.

Store the handler reference and use the same reference for registration and removal.

For component-specific DOM interactions, Angular's template event bindings are often simpler than manually registering browser listeners. Use manual listeners when the integration genuinely requires them.

Preventing Stale Asynchronous Requests

One of the most important uses of effect cleanup is cancelling obsolete asynchronous work.
Imagine a component that loads customer details whenever customerId changes. If the user switches from customer 1 to customer 2 before the first request finishes, the first response might arrive last.

Without appropriate handling, outdated data could overwrite the newer result.

An effect can use AbortController to cancel a previous fetch operation when the effect reruns or is destroyed.
import { Component, effect, signal } from '@angular/core';

@Component({
  selector: 'app-customer-details',
  standalone: true,
  template: `
    <p>Selected customer: {{ customerId() }}</p>
    <button (click)="selectNextCustomer()">Next Customer</button>
  `
})
export class CustomerDetailsComponent {
  customerId = signal(1);

  constructor() {
    effect((onCleanup) => {
      const customerId = this.customerId();
      const controller = new AbortController();

      onCleanup(() => {
        controller.abort();
      });

      void fetch(`/api/customers/${customerId}`, {
        signal: controller.signal
      })
        .then(response => {
          if (!response.ok) {
            throw new Error(
              `Request failed with status ${response.status}`
            );
          }

          return response.json();
        })
        .then(customer => {
          console.log('Loaded customer:', customer);
        })
        .catch(error => {
          if (error.name === 'AbortError') {
            return;
          }

          console.error('Unable to load customer:', error);
        });
    });
  }

  selectNextCustomer(): void {
    this.customerId.update(id => id + 1);
  }
}

When customerId changes, Angular runs the cleanup for the previous effect execution, which aborts its request.

The new effect execution then creates a new controller and starts a request for the current customer.

Registering cleanup before starting the request ensures the cancellation mechanism is established as soon as the resource is created.

Cancellation Is Not a Universal Guarantee

Aborting a fetch request is useful, but cancellation does not undo server-side operations that have already completed.
For read requests, cancellation can prevent unnecessary client-side work and help avoid processing obsolete responses. For operations that modify server data, the server may already have received or processed the request.

Applications that perform mutations should use appropriate server-side transaction handling, idempotency controls, and business rules rather than relying on client cancellation alone.

Also, avoid updating component state from obsolete asynchronous operations when the underlying API cannot be cancelled. In those cases, use a request identifier or another explicit stale-result check.

Using DestroyRef for Component-Level Cleanup

Sometimes a resource belongs to the component rather than to an individual effect execution.
Angular provides DestroyRef for registering cleanup logic that runs when the associated lifecycle scope is destroyed.

For example, a component may register a listener that should remain active for the component's entire lifetime:
import {
  Component,
  DestroyRef,
  inject
} from '@angular/core';

@Component({
  selector: 'app-window-monitor',
  standalone: true,
  template: `<p>Window monitor is active.</p>`
})
export class WindowMonitorComponent {
  private readonly destroyRef = inject(DestroyRef);

  constructor() {
    const handler = () => {
      console.log('Window resized');
    };

    window.addEventListener('resize', handler);

    this.destroyRef.onDestroy(() => {
      window.removeEventListener('resize', handler);
    });
  }
}


The event listener is registered once and remains active until the component is destroyed.



AngularJS Hosting Europe - HostForLIFE :: How to Include Validation and Manage Server Errors with Angular Signal Forms?

clock November 2, 2026 13:04 by author Peter

Forms are part of almost every web application. Users fill out registration forms, update their profiles, submit orders, and enter information that the application needs to process. A good form should help users enter correct information and explain what needs to be fixed when something goes wrong.

Angular provides several ways to build forms, including template-driven forms and reactive forms. Signal Forms introduce a signal-based approach to managing form state and validation in Angular applications. With Signal Forms, developers can define a data model, connect it to a form, and add validation rules that react to changes in the form data. This approach can make form logic easier to organize, especially when an application has multiple fields and validation requirements.

Server-side validation is equally important. Even if a form validates every field in the browser, the server must check the submitted data before saving it. When the server rejects a request, the application should show the relevant error next to the field or display a general message when the problem affects the entire form.

In this article, we will build a registration form, add client-side validation, handle server errors, and discuss practical ways to make Angular forms easier to maintain.

Note that Angular Signal Forms are a newer API, and their availability and exact syntax depend on the Angular version being used. The examples below use the Signal Forms API shape available in Angular versions that support it. Verify the current API before using the examples in an application targeting a different release.

What Are Angular Signal Forms?

Angular Signal Forms use Angular signals to manage form data, validation, and field state.
A signal is a reactive value. When its value changes, Angular can update the parts of the application that depend on it.
Traditional reactive forms use classes such as FormGroup, FormControl, and FormArray. Signal Forms take a different approach by connecting a form to a signal-based data model.

For example, a registration form might contain the following fields:
interface RegistrationForm {
  name: string;
  email: string;
  password: string;
}


The form model describes the information the user needs to enter. Validation rules define which values are acceptable.

Signal Forms can be useful when an application needs reactive form state without managing every field through the traditional reactive forms API.

However, Signal Forms should not automatically replace existing reactive forms. Teams should consider their Angular version, current application architecture, and the maturity of the APIs they intend to use.

Setting Up a Signal Form

Before creating a form, confirm that your Angular project supports the Signal Forms API.
For a project using a supported version, you can begin with a simple registration model.

The following example shows the basic structure of a Signal Form. The form function and related validation APIs must be imported from the Signal Forms package provided by your Angular version.
import { Component, signal } from '@angular/core';
import { form } from '@angular/forms/signals';

interface RegistrationForm {
  name: string;
  email: string;
  password: string;
}

@Component({
  selector: 'app-registration',
  standalone: true,
  templateUrl: './registration.component.html'
})
export class RegistrationComponent {
  registration = signal<RegistrationForm>({
    name: '',
    email: '',
    password: ''
  });

  registrationForm = form(this.registration);
}

Here, registration stores the form data in a signal. The form function connects that data to the form state managed by Angular.

When the form values change, the signal-based model can reflect those changes.

This separation also makes the data model easier to reuse in other parts of the component.

Adding Validation Rules

A form should validate user input before sending it to the server. This gives users immediate feedback and avoids unnecessary requests.

For a registration form, common validation requirements include:

  • The name must not be empty.
  • The email address must contain a valid email format.
  • The password must meet the application's minimum length requirement.

Signal Forms provide validation APIs that allow developers to define these rules against the form model.

The following example illustrates a validation schema using the Signal Forms API. Check the exact validator names and signatures supported by your installed Angular version.
import { Component, signal } from '@angular/core';
import {
  email,
  form,
  minLength,
  required
} from '@angular/forms/signals';

interface RegistrationForm {
  name: string;
  email: string;
  password: string;
}

@Component({
  selector: 'app-registration',
  standalone: true,
  templateUrl: './registration.component.html'
})
export class RegistrationComponent {
  registration = signal<RegistrationForm>({
    name: '',
    email: '',
    password: ''
  });

  registrationForm = form(
    this.registration,
    (path) => {
      required(path.name, {
        message: 'Name is required.'
      });

      required(path.email, {
        message: 'Email is required.'
      });

      email(path.email, {
        message: 'Enter a valid email address.'
      });

      required(path.password, {
        message: 'Password is required.'
      });

      minLength(path.password, 8, {
        message: 'Password must contain at least 8 characters.'
      });
    }
  );
}

The schema describes the rules for each field. The name and email fields are required. The email field must also pass email validation, while the password must contain at least eight characters.

The minimum password length in this example is only a basic rule. Real applications should follow their authentication requirements and avoid relying on length alone as a complete password-security policy.

Connecting Validation to the HTML Template

Validation becomes useful when the form displays clear messages to the user.
The template needs to bind each input to the corresponding field in the Signal Form model. It should also display validation errors when appropriate.

The exact field-binding syntax depends on the Signal Forms API version. In supported versions that expose the field directive, a template can follow this pattern:
<form>
  <label for="name">Name</label>

  <input
    id="name"
    type="text"
    [field]="registrationForm.name"
  />

  <label for="email">Email</label>

  <input
    id="email"
    type="email"
    [field]="registrationForm.email"
  />

  <label for="password">Password</label>

  <input
    id="password"
    type="password"
    [field]="registrationForm.password"
  />

  <button type="submit">Register</button>
</form>


This example demonstrates the field-binding structure. A complete implementation should also connect the form submission handler and render validation messages using the field-state properties supported by the installed Angular version.

For example, show an error when a field has been touched or when the user attempts to submit the form. This avoids displaying every validation message immediately when the page first loads.

Handling Server-Side Validation Errors

Client-side validation improves the user experience, but it cannot guarantee that submitted data is valid.

Users can bypass browser validation, modify requests, or submit data through tools other than the application interface. The server must therefore validate every request independently.

Suppose the user enters an email address that is already registered. The browser may accept the format, but the server should reject the registration.

The server might return a response such as:
{
  "errors": {
    "email": [
      "This email address is already registered."
    ]
  }
}


The Angular application should read the response and display the error next to the email field.

This requires a clear agreement between the frontend and backend about the error-response structure.

Creating a Registration Service

An Angular service can handle communication with the backend.

For example:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

interface RegistrationRequest {
  name: string;
  email: string;
  password: string;
}

@Injectable({
  providedIn: 'root'
})
export class RegistrationService {
  private http = inject(HttpClient);

  register(
    request: RegistrationRequest
  ): Observable<void> {
    return this.http.post<void>(
      '/api/register',
      request
    );
  }
}


The service sends the registration data to the backend.

The endpoint shown here is an application-relative example. Replace it with the route used by your backend.

The service does not decide whether the email address is available. That decision belongs to the server, which should enforce the relevant business rules and database constraints.

Displaying Server Errors in the Form

When the server returns a validation error, the component needs to store that error and display it to the user.

The following component example illustrates a common approach. It uses a separate signal to hold server errors so that they are not confused with client-side validation messages.
import { Component, signal, inject } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

import { RegistrationService } from './registration.service';

interface RegistrationForm {
  name: string;
  email: string;
  password: string;
}

@Component({
  selector: 'app-registration',
  standalone: true,
  templateUrl: './registration.component.html'
})
export class RegistrationComponent {
  private registrationService = inject(RegistrationService);

  registration = signal<RegistrationForm>({
    name: '',
    email: '',
    password: ''
  });

  serverErrors = signal<Record<string, string[]>>({});
  generalError = signal('');

  submitRegistration(): void {
    this.serverErrors.set({});
    this.generalError.set('');

    this.registrationService
      .register(this.registration())
      .subscribe({
        next: () => {
          console.log('Registration successful.');
        },
        error: (error: HttpErrorResponse) => {
          const response = error.error;

          if (response?.errors) {
            this.serverErrors.set(response.errors);
          } else {
            this.generalError.set(
              'Registration failed. Please try again.'
            );
          }
        }
      });
  }
}


This component clears previous server errors before submitting a new request. If the backend returns field-level validation errors, the component stores them in serverErrors. If the response does not contain the expected error structure, it displays a general message instead.
The example assumes that the server returns an object containing an errors property. Adjust the response handling to match your backend contract.
It also uses a simple success message for demonstration. In a real application, you would normally navigate to the next screen or display a success notification.

Showing Server Errors in the Template

The template can display server errors near the relevant field.

For example, if the server returns an error for the email address, the application can show that message below the email input.
<form (submit)="$event.preventDefault(); submitRegistration()">
  <label for="email">Email</label>

  <input
    id="email"
    type="email"
    [field]="registrationForm.email"
  />

  @for (
    message of serverErrors()['email'] ?? [];
    track message
  ) {
    <p class="error-message">{{ message }}</p>
  }

  @if (generalError()) {
    <p class="error-message">{{ generalError() }}</p>
  }

  <button type="submit">Register</button>
</form>

This template illustrates the server-error display pattern. Integrate it with the actual form model and validation-message bindings used by your Angular version.
For accessibility, associate error messages with their input fields and use appropriate attributes such as aria-describedby and aria-invalid when an input has an error.

Client-Side Errors vs. Server-Side Errors
Both types of validation are necessary, but they serve different purposes.

AspectClient-Side ValidationServer-Side Validation
Where it runs In the browser On the server
Main purpose Give immediate feedback Enforce application rules
Network request Usually not required Usually requires a request
Security boundary Cannot be trusted alone Must be enforced by the backend
Example Checking whether an email field is empty Checking whether an email address is already registered
User experience Helps users correct simple mistakes quickly Explains errors that depend on server-side data or business rules

A reliable application uses client-side validation for convenience and server-side validation for correctness and security.

Common Mistakes to Avoid
Trusting Client-Side Validation

A user can bypass browser validation and send a request directly to the backend.

Always validate incoming data on the server before processing or saving it.

Showing Only a General Error

If the server identifies a problem with a specific field, show that error near the relevant input whenever possible.
A general message is still useful for unexpected failures, but it should not replace clear field-level feedback.

Keeping Old Server Errors After Editing

An error such as "This email address is already registered" may become outdated after the user changes the email address.

Clear or update relevant server errors when the user edits a field or submits the form again.

Assuming Every HTTP Error Contains Validation Details

A server may return a validation response, an authorization error, a network failure, or an internal server error.
Handle these cases separately where appropriate. Do not assume that every error response contains a field-level errors object.

Exposing Internal Server Details

Do not display stack traces, database errors, or internal implementation details to users.
Return clear validation messages and use appropriate logging for diagnostic information.

Best Practices for Production Applications

  • Keep the form model separate from unrelated component state.
  • Define validation rules close to the form model where practical.
  • Use client-side validation to improve the user experience.
  • Repeat all important validation on the backend.
  • Agree on a consistent error-response structure between frontend and backend.
  • Clear stale server errors when appropriate.
  • Display field-level errors beside the relevant inputs.
  • Provide a general message for network failures and unexpected server responses.
  • Prevent accidental duplicate submissions while a request is in progress.
  • Use accessible labels and error messages.
  • Avoid logging passwords or sensitive form values.
  • Test valid input, invalid input, server rejection, and network failure.

These practices help keep form behavior predictable as the application grows.

Advantages and Disadvantages
Advantages

Signal Forms provide a signal-based approach to form state and validation. They can make the relationship between application data and form state easier to understand.
Separating client-side validation from server-error handling also gives developers a clear way to manage immediate feedback and backend business rules.

Disadvantages

Signal Forms require familiarity with the relevant Angular APIs, and their availability depends on the Angular version. Teams maintaining older applications may need to continue using reactive forms.

Server-error handling also requires careful coordination between the frontend and backend. Inconsistent response formats can make validation logic difficult to maintain.

Summary

Angular Signal Forms offer a signal-based approach to managing form data and validation. They can help developers organize validation rules and build forms that respond to changes in user input. However, client-side validation is only one part of the process. The backend must validate submitted data independently and return clear errors when a request cannot be accepted.

By keeping form state organized, displaying useful validation messages, handling server errors consistently, and testing failure scenarios, developers can build registration forms that are easier to maintain and more reliable for users. Before adopting Signal Forms in an existing project, verify the API available in your Angular version and adapt the examples to its supported syntax. 



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