How do I set a custom response header in Feathers V5?

92 views Asked by At

I need to set up an end point for Prometheus. The end point requires a custom header:

"Content-Type": "text/plain; version=0.0.4; charset=utf-8"

I tried setting up a custom hook (see below), but all it does is add the Content Type to the body of the response.

export const setContentTypeHeader = (context: HookContext) => {
    context.result = {
        ...context.result,
        headers: {
        'X-Custom-Header': 'Hello World'
        }
    };
    // Set the custom header
    context.result.headers['Content-Type'] = promClient.register.contentType;
    console.log(context.result);
};

I use Feathers v5 and generated a metrics service using feathers generate service.

I also tried

app.use((req, res, next) => {
  res.setHeader('Server-Time', +new Date())
  next()
});

but the app object in v5 doesn't support this.

I use typescript and feathers with koa.

1

There are 1 answers

0
Daff On

You can modify the response headers by setting context.http.headers in your hook:

export const setContentTypeHeader = (context: HookContext) => {
    context.http.headers = {
        ...context.http.headers,
        headers: {
        'X-Custom-Header': promClient.register.contentType
        }
    };
};