Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions app/api/route.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import Ably from 'ably';
import jwt from 'jsonwebtoken';

// ensure Vercel doesn't cache the result of this route,
// as otherwise the token request data will eventually become outdated
// and we won't be able to authenticate on client side
export const revalidate = 0;

export async function GET(request) {
const client = new Ably.Rest(process.env.ABLY_API_KEY);
const tokenRequestData = await client.auth.createTokenRequest({
clientId: 'ably-nextjs-demo',
const clientId = request.nextUrl.searchParams.get('clientId') || 'NO_CLIENT_ID_PROVIDED';
const [keyName, keySecret] = process.env.ABLY_API_KEY.split(':');

const now = Math.floor(Date.now() / 1000);
const claims = {
'x-ably-capability': JSON.stringify({ 'chat-demo:*': ['*'] }),
'x-ably-clientId': clientId,
iat: now,
exp: now + 3600,
};

const token = jwt.sign(claims, keySecret, { algorithm: 'HS256', keyid: keyName });

return new Response(token, {
status: 200,
headers: { 'Content-Type': 'application/jwt' },
});
console.log(`Request: ${JSON.stringify(tokenRequestData)}`);
return Response.json(tokenRequestData);
}
14 changes: 13 additions & 1 deletion components/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,19 @@ export default function Chat() {
const [chatClient, setChatClient] = useState(null);

useEffect(() => {
const realtimeClient = new Ably.Realtime({ authUrl: '/api' });
const clientId = `ably-chat-demo-user-${Math.random().toString(36).substring(2, 10)}`;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR description suggests clientId's are generated with crypto.randomUUID(), can we update the PR description please :)

const realtimeClient = new Ably.Realtime({
authCallback: async (tokenParams, callback) => {
try {
const response = await fetch(`/api?clientId=${clientId}`);
const token = await response.text();
callback(null, token);
} catch (error) {
callback(error, null);
}
},
clientId,
});
const client = new ChatClient(realtimeClient);
setChatClient(client);
return () => {
Expand Down
6 changes: 4 additions & 2 deletions components/ChatBox.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React, { useEffect, useState, useRef } from 'react';
import { useMessages } from '@ably/chat/react';
import { useChatClient, useMessages } from '@ably/chat/react';
import styles from './ChatBox.module.css';

export default function ChatBox() {
const { clientId: currentClientId } = useChatClient();
const inputBox = useRef(null);
const messageEndRef = useRef(null);

Expand Down Expand Up @@ -50,8 +51,9 @@ export default function ChatBox() {

const messageElements = messages.map((message, index) => {
const key = message.serial ?? index;
const isSentByMe = message.clientId === currentClientId;
return (
<span key={key} className={styles.message}>
<span key={key} className={isSentByMe ? styles.sentMessage : styles.message}>
{message.text}
</span>
);
Expand Down
10 changes: 10 additions & 0 deletions components/ChatBox.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,13 @@
flex-grow: 0;
border-bottom-left-radius: 0;
}

.sentMessage {
background-color: #005c97;
color: white;
padding: 1em;
border-radius: 10px;
flex-grow: 0;
border-bottom-right-radius: 0;
align-self: flex-end;
}
128 changes: 125 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"dependencies": {
"@ably/chat": "^1.3.1",
"ably": "^2.21.0",
"jsonwebtoken": "^9.0.3",
"next": "^14.2.3",
"react": "^18.2.0",
"react-dom": "^18.2.0"
Expand Down
Loading