Add realtime data and interactive multi-user experiences to your Next.js apps with Ably, without the infrastructure overhead.
Use Ably in your NextJS application using idiomatic, easy to use hooks.
Using this demo you can:
- Send and receive realtime messages
- Get notifications of user presence on channels
- Send presence updates when a new client joins or leaves the demo
This demo is a Next.js project, bootstrapped with create-next-app
. It uses the Ably React Hooks package, 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).
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. Once you have an Ably account:
- Log into your app dashboard.
- 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.
- Click on the “API Keys” tab.
- Copy the secret “API Key” value from your Root key.
- Create a .env file in the root of the demo repository
- Paste the API key into your new env file, along with a env variable for your localhost:
ABLY_API_KEY=your-ably-api-key:goes-here
API_ROOT=http://localhost:3000
First cd into the project root and install the dependencies, then run the development server:
cd next-and-ably
npm install
npm run dev
# or
yarn install
yarn dev
Open http://localhost:3000 with your browser to see the running demo.
You can start editing the page by modifying pages/index.js
. The page auto-updates as you edit the file.
pages/_app.js is where the Ably SDK is configured:
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} />;
}
export default MyApp;
configureAbly
matches the method signature of the Ably SDK - and requires either a string or a AblyClientOptions object. You can use this configuration object to setup your tokenAuthentication. 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 useChannel
hook lets you subscribe to a channel and receive messages from it:
import { useState } from "react";
import { useChannel } from "@ably-labs/react-hooks";
export default function Home() {
const [channel] = useChannel("your-channel", async (message) => {
console.log("Received Ably message", 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.
You can see an example of this in pages/index.js line 11.
The channel
instance returned by useChannel
can be used to send messages to the channel. It is a regular Ably JavaScript SDK channel
instance.
channel.publish("test-message", { text: "message text" });
You can see an example of this in pages/index.js line 51
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:
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>;
}
You can see an example of this in use in pages/index.js line 16.
You can read more about the hooks available with the Ably Hooks package on the @ably-labs/ably-hooks documentation on npm.
The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js.
Check out the Next.js deployment documentation for more details.
Want to contribute to this project? Have a look at our contributing guide!