Skip to content

Commit a1aecd4

Browse files
authored
Add documentation to authenticate Ably client
Frontend shouldn't expose API key. Alternatively, it should use token that is generated by the backend.
1 parent a7d8181 commit a1aecd4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

docs/react.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,40 @@ root.render(
5151
);
5252
```
5353

54+
However, exposing API key in the client app isn't the best practice. Alternatively you can use the auth callback to provide the token needed to establish the connection.
55+
```tsx
56+
import { AblyProvider } from 'ably/react';
57+
import * as Ably from 'ably';
58+
59+
const BACKEND_URL = "YOUR_BACKEND_URL"
60+
61+
const client = new Ably.Realtime({
62+
authCallback: async (_, callback) => {
63+
let token: Ably.TokenDetails | null = null;
64+
65+
try {
66+
const response = await fetch(BACKEND_URL, {
67+
method: "POST",
68+
});
69+
const token = response.json(); // adjust it based on your backend data structure
70+
} catch (e) {
71+
callback(e instanceof Error ? e.message : "Unknown error occurred", null);
72+
return;
73+
}
74+
75+
callback(null, token);
76+
}
77+
});
78+
79+
root.render(
80+
<AblyProvider client={client}>
81+
<App />
82+
</AblyProvider>,
83+
);
84+
```
85+
86+
More about token generation please refer to this [documentation](https://ably.com/docs/auth/token?lang=javascript#ably-token).
87+
5488
### Define Ably channels
5589

5690
Once you've set up `AblyProvider`, define Ably channels you want to use by utilizing the `ChannelProvider` component:

0 commit comments

Comments
 (0)