TypeScript add custom Request header in Express TypeScript add custom Request header in Express express express

TypeScript add custom Request header in Express


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    }}


For whatever reason, it thinks the string you are passing in is an array, but besides that point, if you need to set a custom header (and it is not a dynamic value) you can use the @Header() decorator. If it is dynamic then you can use an interceptor to grab the response pre-flight and set the header there with something like

@Injectable()export class CustomHeaderInterceptor implements NestInterceptor {  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {    return next      .handle()      .pipe(        tap(() => context.switchToHttp().getResponse().header('XYZ-Token', customValue),      );  }}