How do I set the response header from a server using an apollo server?
Asked Answered
P

1

7

I have an application that updates the users token when it's expired. I need to update the client with this token to prevent error. I'm having trouble actually getting the new token to the front end as there appears to be no way to set anything in the response. Im using Graphql and passport on my backend if that helps.

I've tried res.send, res.setheader, etc...

Does anyone know how to send a new header entry from apollo server to apollo client?

Proliferate answered 26/11, 2018 at 4:8 Comment(2)
Could you just stick the token in the standard response body rather than the header?Trolley
Did you try ApolloLink ? this seems to be an ideal fit for using ApolloLinkPedicure
I
0

I think the formatResponse argument to your ApolloServer constructor should help you. This allows you to process responses from the server before they are sent to client applications. The function takes a GraphQLResponse and GraphQLRequestContext as input and returns a GraphQLResponse. The interface for GraphQLResponse is as follows:

export interface GraphQLResponse {
  data?: Record<string, any> | null;
  errors?: ReadonlyArray<GraphQLFormattedError>;
  extensions?: Record<string, any>;
  http?: Pick<Response, 'headers'> & Partial<Pick<Mutable<Response>, 'status'>>;
}

This means that you can configure your server with the additional argument to parse responses before they are sent to the client:

const myServer = new ApolloServer(
   ...,
   formatResponse: (response, requestContext) => {
       // then create a new response here with your additional headers and return it, for instance
       const newResponse = { ...response, http: { response.http, { headers: ...response.http.headers, newHeader: newValue };
       return newResponse;
   }

Note that the above is only a skeleton, you will need to check the response object more thoroughly than that as its properties are largely optional, but this should give you the gist.

For more details see the documentation here

Informality answered 19/10, 2021 at 14:12 Comment(1)
formatResponse has been deprecated at v4, use plugins instead. see github.com/apollographql/apollo-server/blob/…Wales

© 2022 - 2024 — McMap. All rights reserved.