Incorporate New Element into the Express Request Object

I am attempting to enhance the Express request object by adding a property called "forwardingUrl".

To achieve this, I utilized declaration merging in a file named ./typing.d.ts:

declare namespace Express {
  export interface Request {
    forwardingUrl: string;
  }
}

Although I can access and use the property in the editor, I encounter an error during compilation:

Property 'forwardingUrl' does not exist on type 'Request<ParamsDictionary>'.

What could be causing this issue?

UPDATE

The section of code where the error arises:

import { Middleware, Request } from '@tsed/common';
import { Request as ExpressRequest } from 'express';
@Middleware()
export class Wso2ForwardingUrlParser {
    async use(@Request() request: ExpressRequest) {
        if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {
            request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;
        }   else {
            request.forwardingUrl = '';
        }
    }
}

Answer №1

Implement a new model that extends Request class

import {Request} from "@tsed/common";

export interface CustomRequest extends Request {
    forwardingUrl: string
}

Next, utilize this model in a method

import { Middleware, Request } from '@tsed/common';
import { Request as ExpressRequest } from 'express';
@Middleware()
export class ForwardingUrlParser {
    async use(@Request() request: CustomRequest) {
        if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {
            request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;
        }   else {
            request.forwardingUrl = '';
        }
    }
}

Answer №2

Encountered the same problem and found a solution by including //@ts-ignore right above the lines where the error occurs:

import { Middleware, Request } from '@tsed/common';
import { Request as ExpressRequest } from 'express';

@Middleware()
export class Wso2ForwardingUrlParser {
    async use(@Request() request: ExpressRequest) {
        if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {

            //@ts-ignore
            request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;

        }   else {

            //@ts-ignore
            request.forwardingUrl = '';
        }
    }
}

Suggest utilizing a param decorator for accessing this value later in the code. With the addition of the "forwardingUrl" property to the request instance through middleware, create a param decorator like this:

// ./ForwardingUrlDecorator.ts

import { createParamDecorator } from '@nestjs/common';

export const ForwardingUrl = createParamDecorator((_data: any, req: any) => {
    return req.forwardingUrl;
});

In your controller, you can then retrieve that value without needing to reference the entire express instance as a parameter in your methods:

import { Controller } from '@nestjs/common';
import { ForwardingUrl } from './ForwardingUrlDecorator';

@Controller()
export class YourController {

    @Get()
    public async getTheThing(@ForwardingUrl() forwardingUrl: string) {
        //...
    }
}

Answer №3

If you want to include custom properties in the Express Request Object within nestjs,

You can achieve this by creating a new directory named express and adding a file named index.d.ts, Here's an example:

export {};

export type _CustomProperty = CustomProperty;

declare global {
  namespace Express {
    interface Request {
      customProp: _CustomProperty;
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The specified resource cannot be found in the CDK Stack Export

I'm facing an issue while trying to import values generated and exported from a cdk stack that deploys into eu-west-1 into a different stack that needs to be deployed into af-south-1. The error message states that the export name does not exist: EU n ...

Creating a Countdown in Javascript Using a Variable

I want the date to change from the first date to the second date. At the start, it should display 'Starts:' in bold followed by the remaining time. Once it switches to the second date, it should show 'Ends:' in bold and then the remaini ...

npm will only update when modifications are made to index.js

Recently diving into the world of React, I've encountered an issue with updating my website when making changes to files within my project. While modifications to the index.js file reflect on the site, any adjustments made to imported apps do not get ...

The error message "Mongo is not defined" appeared in Meteor version 1.0.3.1

I am in the process of developing a package that aligns with the guidelines in the Discover Meteor book. You can find more information about this process in the following link: Below is a snippet of my package.js file: api.use(['email1','e ...

Creating a water vessel design using CSS

Despite going through the JS tutorial, I still struggle with it and need some assistance. I believe using a jsfiddle would be helpful. I am attempting to use JS to create a small box that changes color from green to empty based on the fullness of a "wate ...

Incorporating Angular 2: Fetching information from a server data source and integrating it with my ng

Is there a way to load server data from the ng2-smart table plugin in Angular2? I have some product data retrieved from a Node API and I am able to display it onClick event in the browser log. I need to display the same data in the 3rd party plugin' ...

Instructions on how to refresh a FullCalendar component in Vue.js

I am currently using the fullCalendar library for vuejs and facing an issue where I need to refresh the component after deleting an event. <div> <FullCalendar :key="componentKey" v-model="FullCalendar" locale="es" :plugins="calen ...

Utilize Javascript to interact with specific Objects

Working with Node.js, I have written a code that produces the following output: entries: [ { data: [Object] }, { data: [Object] }, { data: [Object] }, ... { data: [Object] } ] } null The code snippet is as follows: targetingIdea ...

What is the best way to retrieve an element from a JavaScript object?

What is the best way to retrieve an item from a JavaScript object? var items = [ { ITEM:1, AMOUNT:10 }, { ITEM:2, AMOUNT:20 } ]; I am looking for a method that allows me to achieve the following: $(items).filter(ITEM == 1).AMOUNT ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

evt.target consistently returns the initial input within the list of inputs

My React file uploader allows users to attach multiple file attachments. Each time a user clicks on an input, I retrieve the data-index to identify the input position. renderFileUploader() { let file_attachment = this.state.file_attachment.map(fun ...

Leverage all the documents obtained from a collection to reference in a Vue component

I am attempting to display all documents from a Firestore collection in a table using refs, but I am unsure about accessing each field for template ref. getDocs(collection(db, "usr")) .then((querySnapshot) => { querySnapshot.forEach((doc ...

Storing Tags with jQuery Tag-it: A guide to saving user inputted tags in an object

Recently stumbled upon a fantastic plugin called tagit, and now I'm looking for a way to extract tag values from it and convert them into an object. Any assistance on this matter would be greatly welcomed! ...

Unique Menu: Challenge when adjusting the width of 5 divs upon hovering while maintaining full site width at 100%

I'm looking to create a sleek custom menu with 5 fields. I want the field under the mouse to expand in width on mouseover, while the other fields shrink in width. The issue I'm facing is that the transition effect is not smooth and the total wid ...

Modify a particular attribute in an array of objects

I am currently working on an Angular project and dealing with the following array object: { "DATA": [ { "CUSTOM1": [ { "value": "Item1", ...

Retrieve data from an HTML form within an Angular 2 ag-grid component

I'm facing a challenge with incorporating form values from a modal into an ag-grid array in my HTML file. I'm unsure of the process to achieve this. Below is an excerpt from my file.html: <template #addTrainContent let-c="close" let-d="dismi ...

Employing jQuery with dynamic content within this context

Can anyone help me with jQuery and dynamic content? I'm trying to prepend items to a list and show the contents of a specific item when clicked, but all items' content is being displayed instead. I attempted using (this) without success. $(docum ...

Utilize the for loop with a specific variable

I am in the process of streamlining my code due to repetitive sections. I anticipate needing to utilize this particular example numerous times. My goal is to implement a for loop, but I'm encountering difficulty with increasing my variable. Currently, ...

Collect information from forms and save it to a mobile phone number

Is it possible to forward form field details to a cell phone number via text message? Here is the code I currently have for sending form data to an email address. If any adjustments need to be made, please provide instructions. <?php if(isset($_POST[ ...

Clicking on an absolute HTML element will instantly scroll back to the top of the page

Working on a website, I've designed a custom menu that is hidden with 0 opacity and z-index -1. When a button is clicked, the menu will appear on the screen. You can visit to see the site in action. The issue I'm facing is that every time I cl ...