Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

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']

1 Answer

0 votes
by (25.1k points)

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),

      );

  }

}

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...