Using TypeScript to Implement Content Security Policy Nonce

I encountered an issue with my TypeScript Express project while attempting to implement a CSP Nonce using Helmet.

app.use(helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
        scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
    }
}));

Upon running the program, I received the following error message:

./index.ts:820
return new TSError(diagnosticText, diagnosticCodes);
       ^
TSError: ⨯ Unable to compile TypeScript:
src/app.ts:17:59 - error TS2339: Property 'locals' does not exist on type 'ServerResponse'.

17         scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
                                                         ~~~~~~

at createTSError (/home/frdiolin/WebstormProjects/Calender2.0/node_modules/ts-node/src/index.ts:820:12)
...

The interesting part is that the same code runs without any issues in JavaScript. Can someone shed some light on what might be causing this discrepancy?

Answer №1

To put it simply: convert res to an Express Response. Check out the code snippet provided below.

This issue is specific to TypeScript only. While res.locals is a feature of Express, Helmet is intended to function independently of Express, which means res.locals are not included in Helmet's types. Essentially, res does not recognize a .locals property because Helmet does not presume it exists.

You can resolve this by specifying to TypeScript that this is an Express response object. Use res as Response.

Here is an illustration:

import express, { Response } from "express";

// ...

app.use(
  helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
      scriptSrc: [
        "'self'",
        // The `res as Response` is crucial here.
        (_req, res) => `'nonce-${(res as Response).locals.cspNonce}'`,
      ],
    },
  })
);

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

Exploring the Usage of Jasmine Testing for Subscribing to Observable Service in Angular's OnInit

Currently, I am facing challenges testing a component that contains a subscription within the ngOnInit method. While everything runs smoothly in the actual application environment, testing fails because the subscription object is not accessible. I have att ...

Creating a different type by utilizing an existing type for re-use

Can you help me specify that type B in the code sample below should comprise of elements from interface A? The key "id" is mandatory, while both "key" and "value" are optional. interface A { id: string; key: string; value: string | number; } /** ...

What steps are necessary to integrate barrel file imports with my Angular 2 application?

Following the Angular 2 style guideline 04-10 Create and Import Barrels can be challenging, as it may lead to unexpected file loading issues. When running my app, I noticed that Angular attempts to load a non-existent file named "my-component-name-here.js" ...

``Should one prioritize the use of Generics over Inheritance, or is there a better way

We are currently in the process of implementing new contracts for our icons system, and we have encountered a debate on which approach is more preferable. Both options result in the same interface: Using Generics -> Although the interface may be less ...

Tips for fetching individual item information from Firebase real-time database using Angular 9 and displaying it in an HTML format

product.component.ts import { AngularFireDatabase } from '@angular/fire/database'; import { ProductService } from './../product.service'; import { ActivatedRoute } from '@angular/router'; import { Component, OnInit} from &apo ...

Node.js Link Management: A Guide to Updating Links

For some time now, I've been attempting to update the tabs on my navigation bar (including the links) when a user logs in. The issue arises on the index page, where users can access it both when logged in and not logged in. In my navigation bar, all t ...

showing javascript strings on separate lines

I need assistance with displaying an array value in a frontend Angular application. How can I insert spaces between strings and show them on two separate lines? x: any = [] x[{info: "test" + ',' + "tested"}] // Instead of showing test , teste ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

Having trouble with JavaScript's Date.getUTCMilliSeconds() function?

I have a straightforward question for you. Take a look at this Angular App and try to create a new date, then print the number of UTC milliseconds of that date in the console. Can you figure out why it is returning zero? ...

Modifying tooltip format in React ApexChart from dots to commas

I am in the process of creating an app targeted towards German users, who traditionally use commas (20,00) instead of dots (20.00) for numbers. I am using react-apexcharts and struggling to figure out how to replace the dots with commas in both my chart an ...

Tips for saving images in an S3 bucket

Within my express application, I currently save images to a directory in my repository. However, I am beginning to think that this approach may not be ideal and I am considering using AWS S3 as an alternative storage solution. Since I have never worked w ...

Leverage the power of TypeScript by enabling the noImplicitAny flag when working

Currently, I am looking to activate the noImplicitAny flag in my compiler. My main issue lies with utilizing lodash/fp as there are no typings available at this moment. Due to this, the compiler is generating errors due to the absence of a definition file ...

Confusing generic function overload in TypeScript

During my exploration of TypeScript, I came across an unusual situation. function concat5<T>(strs: T, strs2: T): T; function concat5(strs: string, strs2: string) { return strs + strs2; } concat5(123, 12); concat5({a:1}, {b:2}); Upon reviewing ...

It is not possible to include parameters in mongoose schema that have not been defined

Is it possible to add new parameters in a MongoDB collection that are not defined in the Mongoose schema? Below is the current schema: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UsersSchema = new Schema({ FirstNam ...

Angular2: Learn how to dynamically create input fields when a button is clicked

My current challenge involves replicating input fields on click of a button. I have a set of input fields where data can be entered, and then I need to add another set of the same fields for additional data. There needs to be a way to remove these replicat ...

Setting up amp CORS using express

I currently have an express application running on Firebase Functions along with a static website hosted on Firebase Hosting. The static website is an AMP website that contains a form which sends a post request to the express app. However, upon submission ...

My Node/Express application is failing to recognize updates made to my Pug view files

I have a Node/Express app that utilizes the Pug/jade template engine, and I am able to render everything successfully. However, I am facing an issue where modifications made to my index.pug file do not reflect on the homepage, even after restarting the ser ...

How to separate an array of objects into individual arrays using Typescript reduce based on a specific property

I have the following array: statisticsOfScrapDeliveriesItems:[ { supplierId: "0001055404", deliveredFrom: "METALLCO AS", centerId: "C45", materialId: "TS0180", }, { sup ...

What is the significance of an equals sign being located within the angle brackets of a type parameter?

Within the type definitions for Bluebird promises, there is a catch function that has the following definition: catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>; The symbol "R" is derived fr ...

What are the available events offered by Express websockets?

I am interested in learning about the different websocket events available. Currently, I have only used the ws.on('message') event, but I would like to find out how to detect when the connection is established and closed. I attempted to add the w ...