Skip to content
Open
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
175 changes: 103 additions & 72 deletions examples/with-ably/README.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
# Realtime Edge Messaging with [Ably](https://ably.com/)
# Realtime messaging with [Ably](https://ably.com/)

**Demo:** [https://next-and-ably.vercel.app/](https://next-and-ably.vercel.app/)

Add realtime data and interactive multi-user experiences to your Next.js apps with [Ably](https://ably.com/), without the infrastructure overhead.

Use Ably in your Next.js application using idiomatic, easy to use hooks.
Use Ably in your Next.js App Router application with the `ably/react` hooks.

Using this demo you can:

- [Send and receive](https://ably.com/docs/realtime/messages) realtime messages
- Get notifications of [user presence](https://ably.com/docs/realtime/presence) on channels
- Send [presence updates](https://ably.com/docs/api/realtime-sdk/presence#update) when a new client joins or leaves the demo

This demo is uses the [Ably React Hooks package](https://www.npmjs.com/package/@ably-labs/react-hooks), a simplified syntax for interacting with Ably, which manages the lifecycle of the Ably SDK instances for you taking care to subscribe and unsubscribe to channels and events when your components re-render).
This demo uses the Ably React hooks that ship with the [`ably`](https://www.npmjs.com/package/ably) package, which manages the lifecycle of the Ably SDK instances for you, subscribing and unsubscribing to channels and events as your components mount and unmount.

## Deploy your own

**You will need an Ably API key to run this demo, [see below for details](#ably-setup)**
**You will need an Ably API key to run this demo. [See below for details](#ably-setup).**

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-ably&project-name=with-ably&repository-name=with-ably)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-ably&project-name=with-ably&repository-name=with-ably&env=ABLY_API_KEY&envDescription=Ably%20API%20key%20from%20https%3A%2F%2Fably.com%2F)

## How to use

Expand All @@ -38,101 +38,132 @@ pnpm create next-app --example with-ably with-ably-app

Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).

**When deployed, ensure that you set your environment variables (the Ably API key and the deployed Vercel API root) in your Vercel settings**
**When deployed, ensure that you set your `ABLY_API_KEY` environment variable in your Vercel project settings.**

## Notes

### Ably Setup
### Ably setup

In order to send and receive messages you will need an Ably API key.
If you are not already signed up, you can [sign up now for a free Ably account](https://www.ably.com/signup). Once you have an Ably account:

1. Log into your app dashboard.
2. Under **Your apps**, click on **Manage app** for any app you wish to use for this tutorial, or create a new one with the Create New App button.
3. Click on the **API Keys** tab.
4. Copy the secret **API Key** value from your Root key.
5. Create a .env file in the root of the demo repository
6. Paste the API key into your new env file, along with a env variable for your localhost:
2. Under **"Your apps"**, click on **"Manage app"** for any app you wish to use for this tutorial, or create a new one with the "Create New App" button.
3. Click on the **"API Keys"** tab.
4. Copy the secret **"API Key"** value from your Root key.
5. Create a `.env.local` file in the root of the project.
6. Paste the API key into your new env file:

```bash
ABLY_API_KEY=your-ably-api-key:goes-here
API_ROOT=http://localhost:3000
```

### How it Works/Using Ably

#### Configuration

[pages/\_app.js](pages/_app.js) is where the Ably SDK is configured:

```js
import { configureAbly } from "@ably-labs/react-hooks";

const prefix = process.env.API_ROOT || "";
const clientId =
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);

configureAbly({
authUrl: `${prefix}/api/createTokenRequest?clientId=${clientId}`,
clientId: clientId,
});

function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
### How it works

#### Client provider

[`app/ably-client-provider.tsx`](app/ably-client-provider.tsx) is a Client Component that creates the Ably Realtime client inside a `useEffect`, so no connection is attempted during SSR. It wraps the app in `AblyProvider` (and `ChannelProvider`) from `ably/react`, making the hooks available to child Client Components:

```tsx
"use client";

import { useEffect, useState } from "react";
import * as Ably from "ably";
import { AblyProvider, ChannelProvider } from "ably/react";

export default function AblyClientProvider({
children,
}: {
children: React.ReactNode;
}) {
const [clientId] = useState(
() =>
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15),
);
const [client, setClient] = useState<Ably.Realtime | null>(null);

useEffect(() => {
const ably = new Ably.Realtime({
authUrl: `/api/createTokenRequest?clientId=${clientId}`,
clientId,
});
setClient(ably);
return () => {
ably.close();
};
}, [clientId]);

if (!client) return <>{children}</>;

return (
<AblyProvider client={client}>
<ChannelProvider channelName="some-channel-name">
<ChannelProvider channelName="your-channel-name">
{children}
</ChannelProvider>
</ChannelProvider>
</AblyProvider>
);
}

export default MyApp;
```

`configureAbly` matches the method signature of the Ably SDK - and requires either a string or a [AblyClientOptions](https://ably.com/docs/api/realtime-sdk#client-options) object. You can use this configuration object to setup your [tokenAuthentication](https://ably.com/docs/core-features/authentication#token-authentication). If you want to use the usePresence function, you'll need to explicitly provide a `clientId`.

You can do this anywhere in your code before the rest of the library is used.
The client is authenticated via a [token request](https://ably.com/docs/core-features/authentication#token-authentication) served by a Route Handler at [`app/api/createTokenRequest/route.ts`](app/api/createTokenRequest/route.ts), so your `ABLY_API_KEY` is never exposed to the browser.

#### useChannel (Publishing and Subscribing to Messages)
#### useChannel (publishing and subscribing to messages)

The `useChannel` hook lets you subscribe to a channel and receive messages from it:

```js
```tsx
"use client";

import { useState } from "react";
import { useChannel } from "@ably-labs/react-hooks";
import { useChannel } from "ably/react";
import type * as Ably from "ably";

export default function Home() {
const [channel] = useChannel("your-channel", async (message) => {
export default function ChatArea() {
const [messages, setMessages] = useState<Ably.Message[]>([]);

const { channel } = useChannel("some-channel-name", (message) => {
console.log("Received Ably message", message);
setMessages((prev) => [...prev, message]);
});
}
```

Every time a message is sent to `your-channel` it will be logged to the console. You can do whatever you need to with those messages.

##### Publishing a message

The `channel` instance returned by `useChannel` can be used to send messages to the channel. It is a regular Ably JavaScript SDK `channel` instance.
// publish a message
const send = () => channel.publish("test-message", { text: "hello" });

```javascript
channel.publish("test-message", { text: "message text" });
return <button onClick={send}>Send</button>;
}
```

#### usePresence

The `usePresence` hook lets you subscribe to presence events on a channel - this will allow you to get notified when a user joins or leaves the channel. The presence data is automatically updated and your component re-rendered when presence changes:

```js
import { useState } from "react";
import { usePresence } from "@ably-labs/react-hooks";

export default function Home() {
const [presenceData, updateStatus] = usePresence("your-channel-name");

const presentClients = presenceData.map((msg, index) => (
<li key={index}>
{msg.clientId}: {msg.data}
</li>
));

return <ul>{presentClients}</ul>;
#### usePresence and usePresenceListener

`usePresence` enters presence and lets you update your presence data. `usePresenceListener` subscribes to presence changes on a channel:

```tsx
"use client";

import { usePresence, usePresenceListener } from "ably/react";

export default function Presence() {
const { updateStatus } = usePresence("your-channel-name");
const { presenceData } = usePresenceListener("your-channel-name");

return (
<>
<button onClick={() => updateStatus("hello")}>
Update status to hello
</button>
<ul>
{presenceData.map((msg, i) => (
<li key={i}>
{msg.clientId}: {String(msg.data ?? "")}
</li>
))}
</ul>
</>
);
}
```

You can read more about the hooks available with the Ably Hooks package on the [@ably-labs/ably-hooks documentation on npm](https://www.npmjs.com/package/@ably-labs/react-hooks).
You can read more about the hooks in the [Ably React docs](https://ably.com/docs/getting-started/react).
64 changes: 64 additions & 0 deletions examples/with-ably/app/ably-client-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"use client";

import {
createContext,
useContext,
useEffect,
useState,
type ReactNode,
} from "react";
import * as Ably from "ably";
import { AblyProvider, ChannelProvider } from "ably/react";

const AblyReadyContext = createContext(false);

export function useAblyReady() {
return useContext(AblyReadyContext);
}

function randomClientId() {
return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
);
}

export default function AblyClientProvider({
children,
}: {
children: ReactNode;
}) {
const [clientId] = useState(() => randomClientId());
const [client, setClient] = useState<Ably.Realtime | null>(null);

useEffect(() => {
const ably = new Ably.Realtime({
authUrl: `/api/createTokenRequest?clientId=${clientId}`,
clientId,
});
setClient(ably);
return () => {
ably.close();
};
}, [clientId]);

if (!client) {
return (
<AblyReadyContext.Provider value={false}>
{children}
</AblyReadyContext.Provider>
);
}

return (
<AblyProvider client={client}>
<ChannelProvider channelName="some-channel-name">
<ChannelProvider channelName="your-channel-name">
<AblyReadyContext.Provider value={true}>
{children}
</AblyReadyContext.Provider>
</ChannelProvider>
</ChannelProvider>
</AblyProvider>
);
}
17 changes: 17 additions & 0 deletions examples/with-ably/app/api/createTokenRequest/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as Ably from "ably";
import { type NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
if (!process.env.ABLY_API_KEY) {
return NextResponse.json(
{ error: "Missing ABLY_API_KEY environment variable" },
{ status: 500 },
);
}

const client = new Ably.Rest(process.env.ABLY_API_KEY);
const clientId =
request.nextUrl.searchParams.get("clientId") ?? "NO_CLIENT_ID";
const tokenRequestData = await client.auth.createTokenRequest({ clientId });
return NextResponse.json(tokenRequestData);
}
23 changes: 23 additions & 0 deletions examples/with-ably/app/api/send-message/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as Ably from "ably";
import { type NextRequest, NextResponse } from "next/server";
import type { ProxyMessage, TextMessage } from "../../../types";

export async function POST(request: NextRequest) {
if (!process.env.ABLY_API_KEY) {
return NextResponse.json(
{ error: "Missing ABLY_API_KEY environment variable" },
{ status: 500 },
);
}

const body = (await request.json()) as ProxyMessage;
const client = new Ably.Rest(process.env.ABLY_API_KEY);
const channel = client.channels.get("some-channel-name");

const message: TextMessage = {
text: `Server sent a message on behalf of ${body.sender}`,
};
await channel.publish("test-message", message);

return NextResponse.json({ ok: true });
}
Loading