
Building a Real-Time Collaborative Web Application with Next.js 14, AWS AppSync, and Amazon Cognito
Step-by-step guide to developing a secure, real-time collaboration app using Next.js App Router, AWS AppSync managed GraphQL subscriptions over WebSockets, and Amazon Cognito user pools.
Overview
Modern applications require real-time updates—from collaborative whiteboards to live order tracking. Managing stateful WebSocket servers at scale is notoriously difficult.
AWS AppSync removes this burden by offering fully managed GraphQL APIs with out-of-the-box WebSocket subscriptions. Coupled with Amazon Cognito for secure JWT authentication and Next.js 14 App Router, you can build collaborative frontends with enterprise-grade authorization and low latency.
Prerequisites
- Node.js 18+ and
npminstalled.
- An active AWS Account.
- Familiarity with TypeScript and GraphQL schemas.
Step 1: GraphQL Schema Definition
In AppSync, define a GraphQL schema supporting queries, mutations, and real-time subscriptions with
@aws_cognito_user_pools directives:type Task @aws_cognito_user_pools {
id: ID!
title: String!
status: String!
assignee: String
updatedAt: AWSDateTime!
}
type Query {
getTask(id: ID!): Task
listTasks: [Task!]!
}
type Mutation {
createTask(title: String!, status: String!, assignee: String): Task!
updateTask(id: ID!, status: String!): Task!
}
type Subscription {
onTaskUpdated: Task
@aws_subscribe(mutations: ["updateTask", "createTask"])
}
Step 2: Configure Cognito and AppSync Authentication
- Amazon Cognito User Pool: Create a user pool named
collab-app-userswith email authentication enabled.
- AppSync Default Authorization: Select Amazon Cognito User Pool as the primary authorization mode and link it to your newly created pool.
- Data Source: Connect an Amazon DynamoDB table (
TasksTable) as the resolver target for your queries and mutations.
Step 3: Front-End Integration with AWS Amplify Client
Install the modular AWS Amplify SDK in your Next.js application:
npm install aws-amplify @aws-amplify/adapter-nextjs
Initialize Amplify inside a client-side provider (
app/providers.tsx ):
'use client';
import { Amplify } from 'aws-amplify';
Amplify.configure({
Auth: {
Cognito: {
userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID!,
userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID!,
}
},
API: {
GraphQL: {
endpoint: process.env.NEXT_PUBLIC_APPSYNC_ENDPOINT!,
region: 'us-east-1',
defaultAuthMode: 'userPool'
}
}
}, { ssr: true });
export function Providers({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
Step 4: Subscribing to Live Updates in React
Use the AppSync WebSocket client to listen for real-time mutations directly in your UI component:
'use client';
import { useEffect, useState } from 'react';
import { generateClient } from 'aws-amplify/api';
const client = generateClient();
const onTaskUpdatedSubscription = /* GraphQL */ `
subscription OnTaskUpdated {
onTaskUpdated {
id
title
status
assignee
}
}
`;
export default function TaskBoard() {
const [tasks, setTasks] = useState<any[]>([]);
useEffect(() => {
// Open WebSocket Subscription to AppSync
const sub = client.graphql({
query: onTaskUpdatedSubscription
}).subscribe({
next: ({ data }) => {
const updatedTask = data.onTaskUpdated;
setTasks((prev) => {
const index = prev.findIndex((t) => t.id === updatedTask.id);
if (index > -1) {
const next = [...prev];
next[index] = updatedTask;
return next;
}
return [updatedTask, ...prev];
});
},
error: (err) => console.error('Subscription error:', err)
});
return () => sub.unsubscribe();
}, []);
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-4">Live Task Board</h1>
<div className="grid gap-3">
{tasks.map((task) => (
<div key={task.id} className="p-4 border rounded shadow-sm bg-slate-900 text-white">
<h2 className="font-semibold">{task.title}</h2>
<span className="text-xs bg-cyan-700 px-2 py-1 rounded">{task.status}</span>
</div>
))}
</div>
</div>
);
}
Key Takeaway
Using AppSync for subscriptions offloads WebSocket connection management, authentication checks, and horizontal broadcasting to managed AWS infrastructure, allowing your Next.js application to remain lightweight and horizontally scalable.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article