Integrate Neon Postgres with Clerk
You will learn the following:
- Use Clerk to authenticate access to your application backed by Neon.
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.
Create a new Next.js project
- Create a new Next.js project using the following command:
- Navigate to the project directory and install the required dependencies:
Integrate the Next.js Clerk SDK
Follow the Next.js quickstart to integrate the Clerk Next.js SDK into your application.
Protect your application routes
To ensure that only authenticated users can access your application, modify clerkMiddleware
to require authentication for every route.
Set your neon connection string
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:
Set up the application schema and database connection
-
Inside the
app/
, create adb/
directory. -
Create a
schema.ts
file in thedb/
directory that defines the database schema. The schema will include a table calleduser_messages
with the columnsuser_id
,create_ts
, andmessage
.Theuser_id
column will be used to store the user's Clerk ID. -
Create an
index.ts
file in thedb
directory to set up the database connection.
Push the schema to the database
-
To load the schema into the database, create a
drizzle.config.ts
file at the root of your project and add the following configuration: -
To push the schema to the database, run the following command:
Create Server Actions to handle user interactions
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.
Create the UI for the Home Page
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 the application
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.
Feedback
Last updated on