{"id":17503,"library":"aws-appsync-auth-link","title":"AWS AppSync Auth Link","description":"The `aws-appsync-auth-link` package provides a specialized Apollo Link for integrating AWS AppSync authentication with Apollo Client in JavaScript and TypeScript applications. It is part of the `aws-mobile-appsync-sdk-js` repository and is currently at version 4.0.2. This link allows developers to configure various AWS AppSync authentication modes, including API Key, AWS IAM, Amazon Cognito User Pools, and OpenID Connect, by injecting the necessary authentication headers into GraphQL requests. Its primary differentiator is its seamless integration with the Apollo Client ecosystem, abstracting away the complexities of signing requests for AppSync. The package's release cadence tends to align with major Apollo Client versions, with a significant jump from v1 to v4 to maintain compatibility with `@apollo/client` v3.x and v4.x, implying potentially infrequent but impactful updates.","status":"active","version":"4.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/awslabs/aws-mobile-appsync-sdk-js","tags":["javascript","typescript"],"install":[{"cmd":"npm install aws-appsync-auth-link","lang":"bash","label":"npm"},{"cmd":"yarn add aws-appsync-auth-link","lang":"bash","label":"yarn"},{"cmd":"pnpm add aws-appsync-auth-link","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for creating Apollo Client instances and linking capabilities.","package":"@apollo/client","optional":false},{"reason":"Core dependency for GraphQL operations.","package":"graphql","optional":false},{"reason":"Used internally for handling asynchronous operations and observables.","package":"rxjs","optional":false}],"imports":[{"note":"Prefer ESM imports for modern applications. CommonJS 'require' style is generally discouraged for new projects.","wrong":"const createAuthLink = require('aws-appsync-auth-link').createAuthLink;","symbol":"createAuthLink","correct":"import { createAuthLink } from 'aws-appsync-auth-link';"},{"note":"An enum providing constants for supported AppSync authentication types (e.g., API_KEY, AWS_IAM, AMAZON_COGNITO_USER_POOLS).","wrong":"const AUTH_TYPE = require('aws-appsync-auth-link').AUTH_TYPE;","symbol":"AUTH_TYPE","correct":"import { AUTH_TYPE } from 'aws-appsync-auth-link';"},{"note":"Type import for configuring the authentication link. Useful for TypeScript projects to ensure correct configuration structure.","symbol":"AuthLinkHTTPOptions","correct":"import type { AuthLinkHTTPOptions } from 'aws-appsync-auth-link';"}],"quickstart":{"code":"import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';\nimport { createAuthLink, AUTH_TYPE } from 'aws-appsync-auth-link';\nimport { createSubscriptionHandshakeLink } from 'aws-appsync-subscription-link';\n\n// Replace with your AppSync endpoint and API key/region\nconst APPSYNC_URL = 'https://YOUR_APPSYNC_ID.appsync-api.YOUR_REGION.amazonaws.com/graphql';\nconst APPSYNC_REGION = 'us-east-1'; // e.g., 'us-east-1'\nconst APPSYNC_API_KEY = process.env.APPSYNC_API_KEY ?? 'da2-YOUR_APPSYNC_API_KEY';\n\n// Configuration object for AppSync\nconst awsAppSyncConfig = {\n  url: APPSYNC_URL,\n  region: APPSYNC_REGION,\n  auth: {\n    type: AUTH_TYPE.API_KEY,\n    apiKey: APPSYNC_API_KEY,\n  },\n};\n\n// 1. Create the authentication link\nconst authLink = createAuthLink(awsAppSyncConfig);\n\n// 2. Create the HTTP link for queries and mutations\nconst httpLink = new HttpLink({ uri: awsAppSyncConfig.url });\n\n// 3. Create the subscription handshake link (required for real-time subscriptions)\n// Note: aws-appsync-subscription-link is a separate package\nconst subscriptionLink = createSubscriptionHandshakeLink(awsAppSyncConfig);\n\n// Chain the links in the correct order:\n// authLink -> subscriptionLink (for WebSocket handshake) -> httpLink (for HTTP requests)\nconst link = authLink.concat(subscriptionLink).concat(httpLink);\n\n// Initialize Apollo Client\nconst client = new ApolloClient({\n  link: link,\n  cache: new InMemoryCache(),\n});\n\nconsole.log('Apollo Client initialized with AWS AppSync authentication and subscription links.');\nconsole.log('AppSync Endpoint:', awsAppSyncConfig.url);\nconsole.log('Authentication Type:', awsAppSyncConfig.auth.type);\n\n// Example of a basic query (requires 'graphql-tag' for gql template literal, not included here)\n// import { gql } from '@apollo/client';\n// client.query({\n//   query: gql`\n//     query MyQuery {\n//       listItems {\n//         items {\n//           id\n//           name\n//         }\n//       }\n//     }\n//   `\n// }).then(response => console.log('Query Data:', response.data))\n//   .catch(error => console.error('Query Error:', error));\n","lang":"typescript","description":"This quickstart demonstrates how to initialize Apollo Client with `aws-appsync-auth-link` and `aws-appsync-subscription-link` for an AppSync API using API Key authentication. It correctly chains the necessary Apollo Links and configures the client."},"warnings":[{"fix":"Migrate your Apollo Client setup to v3.x or v4.x, ensuring `InMemoryCache` and `HttpLink` are correctly imported from `@apollo/client` and links are chained appropriately. Refer to Apollo Client migration guides.","message":"Major breaking changes occurred when upgrading from `aws-appsync` v1.x (and older `aws-appsync-auth-link` versions) due to the underlying Apollo Client peer dependency shifting from v2.x to `>=3.0.0`.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Ensure your `config` object passed to `createAuthLink` includes `url`, `region`, and a correctly structured `auth` object matching your AppSync API's authentication type, including necessary credentials (e.g., `apiKey`, `jwtToken`, `credentials`).","message":"Improperly configured `auth` object in the AppSync configuration can lead to authentication failures (e.g., `Unauthorized` errors) or issues like missing `region` in the request signing process.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Install `aws-appsync-subscription-link` (`npm install aws-appsync-subscription-link`) and integrate `createSubscriptionHandshakeLink` into your Apollo Link chain, usually before the `httpLink`.","message":"For real-time subscriptions with AppSync, `aws-appsync-subscription-link` is typically required alongside `aws-appsync-auth-link` to handle the WebSocket handshake, even if the primary authentication is handled by the auth link.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure the config object passed to `createAuthLink` includes a valid 'region' string, e.g., `{ url: '...', region: 'us-east-1', auth: {...} }`.","cause":"The `region` property is missing or null in the configuration object passed to `createAuthLink` for AWS_IAM or Cognito User Pool authentication.","error":"Unhandled Rejection (Error): No 'region' provided in Auth configuration."},{"fix":"Verify the validity and expiry of your authentication credentials (e.g., API Key, JWT token). For IAM roles, ensure the attached policy grants necessary access to the AppSync API. Double-check your AppSync API's authentication settings in the AWS console.","cause":"The provided authentication credentials (API Key, JWT, IAM role) are invalid, expired, or the principal lacks permissions to access the AppSync API.","error":"Network error: Unauthorized (HTTP Status 401 or 403)"},{"fix":"Ensure all links (`authLink`, `subscriptionLink`, `httpLink`) are correctly instantiated and not `null` before chaining them together using `.concat()`. Check your imports and configuration parameters for any typos or missing values.","cause":"One of the Apollo Link instances (e.g., `authLink`, `subscriptionLink`, `httpLink`) in the chain is `undefined` or `null`, often due to a configuration error or failed import.","error":"TypeError: Cannot read properties of undefined (reading 'concat')"},{"fix":"Install the required peer dependency: `npm install @apollo/client graphql rxjs`","cause":"`@apollo/client` (a peer dependency of `aws-appsync-auth-link`) is not installed in your project.","error":"Module not found: Error: Can't resolve '@apollo/client'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}