Can a serverless Postgres database really handle the demands of a real-time application? The answer lies in pairing it with the right publish-subscribe model. In this guide, you will learn how to combine the real-time capabilities of Ably LiveSync with the structured power of Neon Postgres to build a optimistic and scalable comment system in your Next.js application.
Let’s get started by cloning the Next.js project with the following command:
Once that is done, move into the project directory and install the necessary dependencies with the following command:
The libraries installed include:
ws: A WebSocket library for Node.js.
ably: A real-time messaging and data synchronization library.
@neondatabase/serverless: A serverless Postgres client designed for Neon.
@prisma/client: Prisma’s auto-generated client for interacting with your database.
@prisma/adapter-neon: A Prisma adapter for connecting with Neon serverless Postgres.
@ably-labs/models: A library for working with data models and real-time updates in Ably.
The development-specific libraries include:
tsx: A fast TypeScript runtime for development and rebuilding.
prisma: A toolkit for Prisma schema management, migrations, and generating clients.
Once that's done, copy the .env.example to .env via the following command:
Provision a Serverless Postgres
To set up a serverless Postgres, go to the Neon console and create a new project. Once your project is created, you will receive a connection string that you can use to connect to your Neon database. The connection string will look like this:
Replace <user>, <password>, <endpoint_hostname>, <port>, and <dbname> with your specific details.
Use this connection string as an environment variable designated as DATABASE_URL in the .env file.
Set up Ably LiveSync with Neon Postgres
Sign in into the Ably Dashboard, and click on + Create new app.
Next, name the application and select Data Sync as the type of application you are building.
Next, go to the Integrations tab and click on + New integration rule.
Next, click the Choose button in the Postgres (Alpha) card.
Next, in the integration rule, enter the DATABASE_URL environment variable value obtained and proceed.
Finally, go to the API Keys tab and copy the API Key which has the capabilities as channel metadata, history, presence, privileged headers, publish, push admin, push subscribe, statistics, subscribe.
Use this API Key as an environment variable designated as NEXT_PUBLIC_ABLY_API_KEY in the .env file.
Set up Database Schema
In the file named schema.tsx, you would see the following code:
The code above defines a function that connects to a Neon serverless Postgres database using a DATABASE_URL environment variable and sets up the necessary schema for the real-time application. It creates two tables, nodes and outbox, to store data and manage message processing, respectively. A trigger function, outbox_notify, is implemented to send notifications using pg_notify whenever new rows are inserted into the outbox table. This ensures the database is ready for real-time updates and WebSocket-based communication.
To run the schema against your Neon Postgres, execute the following command:
If it runs succesfully, you should see Database schema set up succesfully. in the terminal.
Set up Prisma for Neon Postgres
In the directory lib/prisma, you would see the following code in index.ts file:
The code above sets up a Prisma client for Neon Postgres. It configures the Neon database connection using the @neondatabase/serverless library, with WebSocket and fetch support to execute queries. A global prisma instance is created using the PrismaNeon adapter, ensuring reuse in development to avoid multiple instances. Finally, the configured prisma client is exported for use throughout the application.
In the same directory, you would see the following code in the api.ts file:
The code above interacts with the Postgres database using Prisma to manage comments. It implements operations like fetching, adding, editing, and deleting comments, with an emphasis on ensuring these operations are recorded in the outbox table for the event-driven system to capturing changes and reflect them in rest of the web clients. Let's understand each function in the code above:
withOutboxWrite(): This higher-order function wraps any operation that modifies the database (such as adding, editing, or deleting a comment) and ensures that the change is also written to the outbox table. It first performs the operation, retrieves the necessary outbox details, and then writes the entry to the outbox table within the same transaction.
getPosts(): Fetches all posts from the database, along with their associated comments and the authors of those comments. The function returns a list of posts, each containing its comments and authors.
getPost(id: number): Promise<[Post, number]>: Fetches a single post by its ID, along with the associated comments and authors. Additionally, it executes a raw SQL query within a transaction to get the next value from a PostgreSQL sequence (outbox_sequence_id_seq), returning this value alongside the post. This ensures that the operation has both the requested post and sequence number, which may be used in event-driven systems for ordering.
getPostTx(tx: TxClient, id: number): A helper function used by getPost() to retrieve a post within a transaction (tx). It ensures the post's comments are fetched in ascending order of their creation timestamp.
getRandomUser(): Retrieves a random user from the database. The function first counts the total number of users and then selects one randomly based on the count.
TxClient: This type represents a transaction client, which is essentially a modified version of the PrismaClient excluding certain methods that are restricted during transactions (ITXClientDenyList).
addComment(): Adds a new comment to a post within a transaction. The function takes in several parameters, such as the transaction client (tx), mutation ID, post ID, author ID, and comment content. It returns an outbox entry that can be used in an event-driven system for tracking the mutation. The outbox entry includes details like the mutation ID, channel (based on the post), event name (addComment), and the newly created comment.
editComment(): Edits an existing comment. It accepts the transaction client (tx), mutation ID, comment ID, and new content. After updating the comment, it returns an outbox entry similar to addComment(), but with the event name editComment.
deleteComment(): Deletes a comment. It takes in the transaction client (tx), mutation ID, and the comment ID to be deleted. Like the other mutation functions, it returns an outbox entry, but with the event name deleteComment.
Create a Real-Time Data Model Client with Ably
In the directory lib/models, you would see the following code in modelsClient.ts file:
In the code above, a function modelsClient is defined which initializes and returns a singleton instance of the ModelsClient from the @ably-labs/models library, using an Ably Realtime connection. It ensures that the client is only instantiated once, leveraging the Ably API key stored in environment variables to create the Realtime connection.
In the same directory, you would see the following code in the mutations.ts file:
In the code above, three asynchronous functions to handle CRUD operations for comments are defined:
addComment: Sends a POST request to add a new comment, including the author's details and content, identified by a mutationId.
editComment: Sends a PUT request to update an existing comment's content by its id.
deleteComment: Sends a DELETE request to remove a comment by its id.
Each function validates the server response and throws an error for unsuccessful requests. Additionally, the merge function handles state updates by applying optimistic or confirmed events, ensuring that the state reflects comment additions, edits, or deletions accurately.
In the same directory, you would see the following code in the hook.ts file:
In the code above, the following function and hook are defined:
getPost: Fetches the initial post data and its sequence ID from an API endpoint.
useModel: Manages a model instance and its associated state. The hook returns the synchronized post data and model instance for use in components. It:
Initializes the model with a channel name, sync function (to fetch data), and merge logic.
Synchronizes the model with the latest data when the id changes.
Subscribes to real-time updates from the model, updating the component state accordingly.
API Routes for Comments and Real-Time Synchronization
To perform server-side operations as a result of user interaction on the webpage, a common pattern is to use API routes. In Next.js, API Routes (aka Endpoint Handlers) can be created by creating a file named route.ts in any directory in the app directory.
To allow dynamic updates and the ability to delete comments, you would see the following code in route.ts file in the app/api/comments/[id] directory:
In the code above, there are two endpoints, PUT and DELETE, both of which parse the id param in the request. The PUT endpoint extracts the comment properties (mutationId, content) to edit the comment in Postgres and sync the changes to the rest of the web clients that are actively looking to stream comment changes in real-time.
To allow the ability to insert comments, you would see the following code in route.ts file in the app/api/comments directory:
In the code above, the endpoint parses the request's body to extract the comment properties (mutationID, postId, authorId, content). Further, it inserts into Postgres using the withOutboxWrite helper function which makes sure to sync it in Postgres and rest of the web clients that are actively looking to stream comments in real-time.
Similarly, you would see the following code in route.ts file in the app/api/posts/[id] directory:
In the code above, the endpoint parses the id param in the request and returns the sequenceId and the comment details associated with that ID in Postgres.
Deploy to Vercel
The repository is now ready to deploy to Vercel. Use the following steps to deploy:
Start by creating a GitHub repository containing your app's code.
Then, navigate to the Vercel Dashboard and create a New Project.
Link the new project to the GitHub repository you've just created.
In Settings, update the Environment Variables to match those in your local .env file.
In this guide, you learned how to build a real-time comment system for a Next.js application by integrating Ably LiveSync with a serverless Neon Postgres database. The tutorial covered setting up the database schema, configuring Prisma for streamlined database access, and implementing Ably for real-time updates. You also explored how to handle optimistic updates, ensure data synchronization, and deploy the application to Vercel.
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. Users on paid plans can open a support ticket from the console. For more details, see Getting Support.