I want to add custom header with value to all responses in NestJS framework (v8). I think the correct way is to use global interceptor, but I can't figure out how to do it.
I am adding my interceptor:
app.useGlobalInterceptors(new HeadersInterceptor());
and I found multiple approaches but none of them work. The most common looks like:
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, tap } from 'rxjs';
@Injectable()
export class HeadersInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
tap(() => {
const res = context.switchToHttp().getResponse();
res.setHeader('my-global-header', 'important-value');
}),
);
}
}
but I'm getting an error:
res.setHeader is not a function
EDIT: Judging from the correct answer I should have mentioned that I'm also using GraphQL.
This depends on which context NestJS is executing. Here I have example for GraphQL and HTTP context.
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Response } from 'express';
import { Observable } from 'rxjs';
@Injectable()
export class VersionHeaderInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// When the request is GraphQL
if ((context.getType() as string) === 'graphql') {
const gqlExecutionContext = GqlExecutionContext.create(context);
const response: Response = gqlExecutionContext.getContext().res;
response.setHeader('x-version', process.env.npm_package_version);
}
// When the request is HTTP
if (context.getType() === 'http') {
const http = context.switchToHttp();
const response: Response = http.getResponse();
response.setHeader('x-version', process.env.npm_package_version);
}
return next.handle();
}
}
You code looks fine. What happens if you try to use Response interface from express?
import { Response } from 'express';
@Injectable()
export class HeadersInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const res: Response = context.switchToHttp().getResponse();
res.setHeader('my-global-header', 'important-value');
return next.handle();
}
}
You could simply use the set
method on the response object
res.set('my-global-header', 'important-value')
I believe the setHeader
is one of the options provided in express.static()
. You could look up the docs on this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.