Skip to content

A simple example of using Ably to send realtime messages in a Next app

License

Notifications You must be signed in to change notification settings

snakemode/next-and-ably

 
 

Repository files navigation

Realtime Edge Messaging in your NextJS apps with Ably

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:

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).

Getting Started

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. 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:
ABLY_API_KEY=your-ably-api-key:goes-here
API_ROOT=http://localhost:3000

Running the Demo

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.

Using Ably

Configuration

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.

useChannel (Publishing and Subscribing to Messages)

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.

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.

channel.publish("test-message", { text: "message text" });

You can see an example of this in pages/index.js line 51

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:

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.

Deploy on Vercel

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.

Contributing

Want to contribute to this project? Have a look at our contributing guide!

More info


Ably logo

About

A simple example of using Ably to send realtime messages in a Next app

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 75.4%
  • CSS 19.8%
  • Shell 2.7%
  • JavaScript 2.1%