This tutorial demonstrates how to integrate Neon Postgres with Clerk in a Next.js application, using drizzle-orm and drizzle-kit to interact with the database. The tutorial guides you through setting up a simple application that enables users to add, view, and delete messages using Server Actions and Middleware with Clerk.
Add the Neon connection string to your project's environment variables. You can find the Neon connection string in the Neon console - see the Neon docs for more information.
Your environment variable file should have the following values:
Create a schema.ts file in the db/ directory that defines the database schema. The schema will include a table called user_messages with the columns user_id, create_ts, and message.The user_id column will be used to store the user's Clerk ID.
Create an index.ts file in the db directory to set up the database connection.
To handle form submissions for adding and deleting user messages, create two Server Actions in app/actions.ts. Use the auth() function from Clerk to obtain the user ID, which will be used to interact with the database.
In your app/page.tsx file, add the following code to create the UI for the home page. If a message exists, the user can view and delete it; otherwise, they can add a new message.
To retrieve the user's messages, use Clerk's auth() to obtain the user's ID. Then, use this ID to query the database for the user's messages.
To enable the user to delete or add a message, use the deleteUserMessage() and createUserMessage() actions created in the previous step.
Run your application and open http://localhost:3000 in your browser. Sign in with Clerk and interact with the application to add and delete user messages.