使用Node.js与EJS时AWS AppSync订阅功能故障求助
Hey there! I’ve run into similar subscription connection headaches with AppSync before, so let’s walk through the most common fixes step by step:
1. Verify Your GraphQL Schema & Subscription Configuration
First, double-check that your schema defines valid subscriptions tied to your DynamoDB mutations. For example:
type Item { id: ID! name: String! } type Mutation { updateItem(id: ID!, name: String!): Item @aws_dynamodb(table_name: "YourTable", operations: [update]) createItem(id: ID!, name: String!): Item @aws_dynamodb(table_name: "YourTable", operations: [put]) } type Subscription { onUpdateItem: Item @aws_subscribe(mutations: ["updateItem"]) onCreateItem: Item @aws_subscribe(mutations: ["createItem"]) }
Make sure each subscription explicitly links to the correct mutation(s) that modify your DynamoDB table.
2. Ensure Client WebSocket Initialization is Correct
You mentioned the MQTT WebSocket isn’t opening—this is almost always a client setup issue. If you’re using AWS Amplify (the recommended approach), confirm your config enables subscriptions:
import Amplify from 'aws-amplify'; import awsconfig from './aws-exports'; // aws-exports should include your AppSync endpoint, auth type, and API key/IAM details Amplify.configure(awsconfig);
If you’re using a custom Apollo Client setup, explicitly create a SubscriptionClient for WebSocket connections:
import { SubscriptionClient } from 'aws-appsync-subscription-link'; import { ApolloClient, InMemoryCache, split } from '@apollo/client'; import { createHttpLink } from 'apollo-link-http'; import { getMainDefinition } from '@apollo/client/utilities'; const httpLink = createHttpLink({ uri: 'YOUR_APPSYNC_HTTP_ENDPOINT' }); const subscriptionClient = new SubscriptionClient( 'YOUR_APPSYNC_WSS_ENDPOINT', // This is a wss:// URL from your AppSync console { auth: { type: 'API_KEY', // Or IAM/AMAZON_COGNITO_USER_POOLS apiKey: 'YOUR_APPSYNC_API_KEY', }, } ); // Route subscriptions through WebSocket, queries/mutations through HTTP const link = split( ({ query }) => { const def = getMainDefinition(query); return def.kind === 'OperationDefinition' && def.operation === 'subscription'; }, subscriptionClient, httpLink ); const client = new ApolloClient({ link, cache: new InMemoryCache() });
3. Check Permissions & CORS Settings
- AppSync Permissions: Ensure your auth method (API Key, IAM role, or Cognito user pool) has permission to run
appsync:StartSubscription. For API Keys, confirm it hasn’t expired. For IAM, add this action to your role’s policy. - CORS Configuration: In the AppSync console’s Settings tab, make sure your frontend domain is allowed in the CORS config. WebSocket connections require CORS permissions too—don’t just set up HTTP CORS and forget WebSocket.
4. Debug the WebSocket Connection
Open your browser’s DevTools > Network tab, filter for "WS" to see if a connection attempt is being made. Common errors to look for:
- 403 Forbidden: Permission issue—double-check your auth credentials or IAM policy.
- Connection Failed: Invalid WebSocket endpoint (copy it directly from the AppSync console’s Settings tab—format is
wss://<api-id>.appsync-api.<region>.amazonaws.com/graphql). - Add error logging to your client to get more details:
subscriptionClient.onError((error) => { console.error('Subscription connection error:', error); });
5. Confirm DynamoDB <-> AppSync Integration
If your subscriptions rely on DynamoDB stream events:
- Ensure your DynamoDB table has streams enabled (in the table’s Overview tab).
- In your AppSync DynamoDB data source, verify you’ve linked the stream ARN and configured the correct trigger mappings for mutations.
Go through these checks one by one—most subscription issues boil down to a small config oversight. Let me know if any of these steps point you to the problem!
内容的提问来源于stack exchange,提问作者Bryan Ho

