jasonkuhrt / graphql-request

Minimal GraphQL client

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to pass headers while using `getServerSideProps`

zgrybus opened this issue · comments

We want to prefetch data by using getServerSideProps. Do we really need to pass headers directly to graphql.request function? Is it possible that following code may work?

export const getServerSideProps = (async context => {
  const { id: postId } = context.query;
  
  const headers = context.req.headers;
  const accessToken = headers['app_header'];

  context.res.setHeader('new_header', accessToken);

  const data =  await graphQLClient.request(query, { postId });

  return data;
}) satisfies GetServerSideProps;

I wouldn't like to pass headers as second argument to the function, since we use react-query ( and we would need to disable eslint deeps rule ).

If someone is interested, I noticed that graphql-request adds possibility to setHeader directly to the object..

export const getServerSideProps = (async context => {
  const { id: postId } = context.query;
  
  const headers = context.req.headers;
  const accessToken = headers['app_header'];

  graphQLClient.setHeader('new_header', accessToken); <--- this line

  const data =  await graphQLClient.request(query, { postId });

  return data;
}) satisfies GetServerSideProps;

Closing this issue :)