Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript add custom Request header in Express

I am trying to add a custom header to my request, but it must be modified/implemented in the interface.

The default Request interface references IncomingHttpHeaders. So I am attempting to extend this interface with my own custom token header.

import { IncomingHttpHeaders } from 'http';

declare module 'express-serve-static-core' {
    interface IncomingHttpHeaders {
        "XYZ-Token"?: string
    }
}

I have updated my .tsconfig file to read the ./types folder. The name of my file is index.d.ts

I can successfully compile the code if I do not use my custom header, but when I try to reference the token header in the code I get the following compilation error:

Error

error TS2538: Type 'string[]' cannot be used as an index type.

    req.headers['XYZ-Token']

If I use any of the values of the original interface everything works fine.

Example:

    req.headers['user-agent']

Additional information: I am using NestJS, which uses Fastify/Express under the hood. I can confirm that the Request interface being used is from Express. Fastify is backwards compatible with all Express modules. Mainly using Fastify because it's faster.

like image 860
Nicholas Porter Avatar asked Nov 21 '19 01:11

Nicholas Porter


1 Answers

Looks like the wrong module name is in the declaration.

Even though the IncomingHttpHeaders interface is being attached to the Request object from express-serve-static-core, the original source of the IncomingHttpHeaders interface is actually part of the http package.

The following allowed the custom header to be accessible in the code and ts compiled correctly.

import { IncomingHttpHeaders } from 'http';

declare module 'http' {
    interface IncomingHttpHeaders {
        "XYZ-Token"?: string
    }
}
like image 77
Nicholas Porter Avatar answered Sep 24 '22 23:09

Nicholas Porter