question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Adding custom headers

See original GitHub issue

Hi,

I am looking for the way to add a custom header in all the request sent to AppSync. I was able to do it with the Amplify library but since I need some the advanced functionnalities from aws-appsync-sdk, I am trying to do it with the appsync-sdk as well.

I didn’t find any documentation on this topic. Is there a way to do it?

For example, I tried to add request option when creating the AWSAppSyncClient without any success:

const appSyncClient = new AWSAppSyncClient({
  url: config.amplify_config.aws_appsync_graphqlEndpoint,
  request: async (operation) => {
    const user = await Auth.currentUserInfo();
    logger.debug("AWSAppSyncClient request:", user);
    operation.setContext({
      headers: {
        'amt-custom-username': user.username
      }
    });
  },
  region: config.amplify_config.aws_appsync_region,
  auth: {
    type: AUTH_TYPE.AWS_IAM,
    credentials: () => Auth.currentCredentials(),
  },
});

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
elorzafecommented, Jun 5, 2018

Hi @OlivierPT

Try this sample code here

In order to read the custom header on your request mapping template use this $context.request.headers.your_header_name

I used this on the previous sample

{
    "version": "2017-02-28",
    "payload": {
    	"id": "${context.arguments.id}",
        "title": "$context.request.headers.hi"
    }
}

Let me know how it goes

1reaction
ziggy6792commented, Sep 8, 2020

@elorzafe you are an absolute legend. Copied your sample into my project and used $context.request.headers.your_header_name in my request mapping to get my custom header. Worked first time!

In my case I am accessing a graphql api through a lambda and using IAM credentials. Here is my code to setup the AWSAppSyncClient if anyone is interested.

const AWS = require('aws-sdk');
const AWSAppSyncClient = require('aws-appsync').default;
const { createAppSyncLink } = require('aws-appsync');
require('es6-promise').polyfill();
require('isomorphic-fetch');
const { ApolloLink } = require('apollo-link');
const { createHttpLink } = require('apollo-link-http');
const { setContext } = require('apollo-link-context');

const buildApiClient = (connection, customHeaders) => {
  const { URL, REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN } = connection;

  AWS.config.update({
    region: REGION,
    credentials: new AWS.Credentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN),
  });
  const { credentials } = AWS.config;

  const AppSyncConfig = {
    url: URL,
    region: REGION,
    auth: {
      type: 'AWS_IAM',
      credentials,
    },
    disableOffline: true,
  };

  const appsyncClient = new AWSAppSyncClient(AppSyncConfig, {
    defaultOptions: {
      query: {
        fetchPolicy: 'network-only',
        errorPolicy: 'all',
      },
    },
    link: createAppSyncLink({
      ...AppSyncConfig,
      resultsFetcherLink: ApolloLink.from([
        setContext((request, previousContext) => ({
          headers: {
            ...previousContext.headers,
            ...customHeaders,
          },
        })),
        createHttpLink({
          uri: AppSyncConfig.url,
        }),
      ]),
    }),
  });

  return appsyncClient;
};

module.exports = buildApiClient;

Read more comments on GitHub >

github_iconTop Results From Across the Web

No results found

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found