Skip to content

Instantly share code, notes, and snippets.

@stefangomez
Created July 1, 2019 04:39
Show Gist options
  • Save stefangomez/7e98dac2ce8e9c95d5216b2277ba4e54 to your computer and use it in GitHub Desktop.
Save stefangomez/7e98dac2ce8e9c95d5216b2277ba4e54 to your computer and use it in GitHub Desktop.
amplify/appsync client setup for cognito authed users + unauthed users via AWS_IAM
import Amplify from "@aws-amplify/core";
import Auth from "@aws-amplify/auth";
import { setContext } from "apollo-link-context";
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
import AWSAppSyncClient, { AUTH_TYPE, createAppSyncLink } from "aws-appsync";
import awsConfig from "../aws-exports";
Amplify.configure({
...awsConfig,
Analytics: { disabled: true }
});
const appsyncClient = new AWSAppSyncClient(awsConfig, {
link: createAppSyncLink({
url: awsConfig.aws_appsync_graphqlEndpoint,
region: awsConfig.aws_appsync_region,
auth: {
type: AUTH_TYPE.AWS_IAM,
credentials: async () => await Auth.currentCredentials()
},
resultsFetcherLink: ApolloLink.from([
setContext(async (request, previousContext) => {
try {
const session = await Auth.currentSession();
if (session) {
delete previousContext.headers["X-Amz-Security-Token"];
return {
headers: {
...previousContext.headers,
Authorization: session.getIdToken().getJwtToken()
}
};
}
} catch (e) {
// log or catch error
}
return {
headers: previousContext.headers
};
}),
createHttpLink({
uri: awsConfig.aws_appsync_graphqlEndpoint
})
])
})
});
export default appsyncClient;
@sebastienfi
Copy link

Thanks for this!
You might need to add complexObjectsCredentials: async () => await Auth.currentCredentials(), betwen L21-L22 to avoid linting, and/or if you intend to upload to S3 from Amplify.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment