Authentication

Realtime offers two authentication options for users. The first method involves using a Public Auth Key, which is a quick and easy setup option. Alternatively, users can choose to implement their own authentication endpoint with a Secret Key. With this method, developers have complete control over the permissions granted to each user, including read and write permissions for documents and presence. By offering these authentication options, Realtime allows developers to customize their authentication process and ensure that users have appropriate access to collaborate in real-time.

Public Auth Key

Using a Public Auth Key for authentication in Realtime is a simple way to access Realtime. To get started, retrieve the Public Auth Key from your Realtime project and make sure it is active.
Then use the publicAuthKey parameter within the Realtime, e.g.
typescript
<RealtimeProvider ... publicAuthToken={process.env.REALTIME_PUBLIC_AUTH_TOKEN} > {/* App content */} </RealtimeProvider>

Monthly Active Users for Public Auth Key

During the authentication process, a random user ID with the prefix public_ is generated. This user ID is unique and is used to identify the user for future requests. The user ID is stored as a cookie so that it can be retrieved and reused for subsequent requests. This avoids generating additional monthly active users, which helps reduce costs for your project.

Setup authentication endpoint

If you setup your own authentication endpoint, you will have complete control over the permissions granted to each user, including read and write permissions for documents and presence.

Your API

The auth endpoint implemented within your system should have the following (or similar) code for getting a Realtime JWT token.
typescript
const permissions = { documents: ['read', 'write'], presence: ['read', 'write'], broadcast: ['read', 'write'], } const realtimeAuthResponse = await fetch('https://worker.inrealtime.app/auth', { method: 'POST', body: JSON.stringify({ apiKey: process.env.REALTIME_SECRET_KEY, userId: userId, permissions: permissions // Optional. Default is all permissions documentId: documentId, // Normal (single document) connections groupId: groupId, // Only for group connections metadata: { // Optional. You can add user metadata here, like name of user, profile picture url, etc. }, }), headers: new Headers({ 'content-type': 'application/json', }), }) const realtimeAuthData = await realtimeAuthResponse.json() const token = realtimeAuthData.token
Parameters
  • apiKey
    • The Secret Key used to authenticate the request. This secret key can be found under settings of your project. You may need to generate it if its your first time.
  • userId
    • A unique identifier for the user who is requesting access to the document. This ID should be unique within your system. The userId is used when determining monthly active users.
  • permissions
    • The user’s permission in the document. If not specified the user will be given full access to the document. If any of the keys are missing (e.g. ‘document’) the default value of it will be attached. The default value is always full permission.
    • In addition to granting specific privileges to users, permissions in Realtime can also be leveraged to provide read-only access to a document. This functionality can be particularly useful for creating efficient, reusable software components, as it eliminates the need to write separate read-only versions of the components.
  • documentId
    • The ID of the document that the user is requesting access to. More documentation on this ID below.
    • Either documentId or groupId needs to be specified
  • groupId
    • Used when using a single connection to connect to multiple documents. More documentation on this below
    • Either documentId or groupId needs to be specified
  • metadata
    • An optional object that contains additional information about the user. This metadata will be accessible by the package by all clients (with the correct permissions), so having things like names, profile picture urls, and more could be useful.
    • The userId and permissions will be attached to metadata during authentication and will also be available to other clients.

Realtime React Package

💡
If the getAuthToken function you provide is within a component, make sure to memoize (e.g. using useCallback or useMemo) it to avoid unnecessary re-connections.
The following code should call your API endpoint.
typescript
export const getRealtimeAuthToken = async ({ documentId groupId }: { documentId?: string groupId?: string }): Promise<string> => { // Either documentId or groupId will be provided, not both. // If the connection is to a single document (the usual) then documentId is provider. // If the connection is to a group then the groupId is provided. const response = await apiClient.post<{ token: string }>('/realtime/auth', { documentId, groupId }) return response.data.token }
Then use the getAuthToken parameter within the Realtime, e.g.
typescript
<RealtimeProvider ... getAuthToken={getRealtimeAuthToken} > {/* App content */} </RealtimeProvider>

Document ID in auth endpoints

When it comes to document authentication in Realtime, there are multiple ways to approach the process. One aspect to consider is where the document ID comes from.
Document authentication in Realtime can be approached in multiple ways, and one important consideration is where the document ID comes from. Depending on your use case and requirements, you may want to consider the following approaches:
  • Server-generated IDs: In this approach, the document ID is generated on your server and passed to the client as part of the authentication process. This can be useful if you have an existing database of documents or things and need to ensure that clients can only access authorized documents.
  • Client-generated IDs: Here, the document ID is generated on the client side and then sent to your server to be stored and associated with the relevant document. This approach can be useful if you want to allow clients to create new documents and maintain control over the document IDs.
  • Combination of approaches: You can also use a combination of these approaches. For instance, you could generate a temporary document ID on the client side and send it to your server to be associated with an existing document. This can be helpful if you want to allow anonymous users to collaborate on a document while still tracking their activity.
  • Multiple ID sources: Alternatively, you could create the document ID from more than one ID within your system. This approach can provide additional security and redundancy.
Here are some examples of different types of document IDs:
  • Customer IDs: Unique identifiers assigned to each customer in a company's database.
  • Game IDs: Unique identifiers assigned to each game in a gaming platform's database.
  • Order IDs: Unique identifiers assigned to each order in an e-commerce company's database.
  • Project IDs: Unique identifiers assigned to each project in a project management system's database.
Overall, the approach you take to document authentication will depend on your specific use case and requirements. The important thing is to ensure that the authentication process is secure, and that only authorized users are able to access and modify documents.
Notes
  • Document IDs can be a maximum of 96 characters long
  • Please note that documents in groups and single document connections are kept separate. Using the same document ID for different groups will result in distinct documents. Similarly, connecting to a document ID with a single document connection and connecting to a group with the same document ID will not yield the same document.

Group ID

Group IDs are a way to connect to multiple documents in a single connection. By grouping related documents together, you can more efficiently manage and subscribe to them, which is especially useful in systems with a large number of documents or where users frequently switch between different documents.
Here are some benefits of using Group IDs:
  • Faster subscribing: With Group IDs, you can subscribe to multiple documents in a single connection, which can improve performance and reduce latency.
  • Easier management: Group IDs can be used to organize documents into logical groups, which makes it easier to manage and maintain large sets of documents.
  • More efficient resource utilization: By subscribing to multiple documents in a single connection, you can reduce the resources required for maintaining multiple connections.
  • Makes it easier to implement Realtime collaboration features in complex systems. By connecting related documents with a Group ID, users can collaborate on multiple documents simultaneously, without the need to switch between different connections or applications. This can lead to more efficient and effective collaboration, which can improve the overall performance of the system.
Notes
  • Group IDs can be used with both public auth keys and auth endpoints
  • Group IDs can be a maximum of 96 characters long
  • Please note that documents in groups and single document connections are kept separate. Using the same document ID for different groups will result in distinct documents. Similarly, connecting to a document ID with a single document connection and connecting to a group with the same document ID will not yield the same document.
Examples of systems that can benefit from Group IDs include:
  • CRM systems: In a CRM system, Group IDs can be used to connect customer records, orders, and invoices, allowing users to view and update all relevant documents in a single connection.
  • Project management systems: In a project management system, Group IDs can be used to connect project tasks, milestones, and deadlines, allowing users to view and update all relevant documents in a single connection.
  • Inventory management systems: Group IDs can be used to connect multiple documents related to a single product, such as inventory levels, purchase orders, and sales history.
  • Gaming systems: In a multiplayer gaming system, Group IDs can be used to connect players, game rooms, and game data, allowing for faster updates and more efficient resource utilization.

Powered by Notaku