
























In this tutorial, you'll build a blog app from scratch using many modern and popular technologies such as Next.js, Clerk, tRPC, Prisma, and more. After reading this guide, you'll have a simple blog application that allows users to create and read posts.
Let's explore the various technologies used in the article:
You'll start by creating a Next.js app and integrating Clerk into it for authentication. Then you'll deploy the application to Vercel, where you will also create a Neon database that will be used by Prisma to access and manipulate data within that database. At this point the application will be fully functional, however the rest of the tutorial further enhances the type-safety of your app by adding Tanstack Query, tRPC, and zod. Finally, you'll learn how to create protected procedures using Clerk's authentication context.
To follow along, you should have Node.js installed on your computer and a Vercel account. Familarity with React and Next.js is recommended as well.
Start by opening your terminal and running the following command to create a new Next.js application. When prompted for the various configuration options, use the options specified below:
Once the application has been created, follow the quickstart in the docs to add Clerk to it.
Alternatively, you can clone the Clerk Next.js quickstart repository. This repository contains a pre-configured Next.js app with Clerk already added in keyless mode, which allows you to test the authentication features in your app locally without having to create an account.
Since keyless mode only works for local development, you will want to create a Clerk account and an application in the dashboard to deploy your application to Vercel.
The Clerk Dashboard is where you, as the application owner, can manage your application's settings, users, and organizations. For example, if you want to enable phone number authentication, multi-factor authentication, social providers like Google, delete users, or create organizations, you can do all of this and more in the Clerk Dashboard.
You need to set your Clerk API keys in your app so that your app can use the configuration settings that you set in the Clerk Dashboard.
.env file, set the NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY environment variables to the values you copied from the Clerk Dashboard.While developing, it's best practice to keep your project running so that you can test your changes as you work. So, let's make sure the app is working as expected.
http://localhost:3000 and will be used through the remainder of the tutorial. It should render a new Next.js app, but with a "Sign in" and "Sign up" button in the top right corner.

<SignIn /> component. The <SignIn /> component will look different depending on the configuration of your Clerk instance.

<UserButton /> component in the top right corner.Run the following command to install Prisma:
Then run npx prisma init to initialize Prisma in your project.
This will create a new prisma directory in your project, with a schema.prisma file inside of it. The schema.prisma file is where you will define your database models.
The prisma init command will also update your .env file to include a DATABASE_URL environment variable, which is used to store your database connection string. If you have a database already, great! If not, let's spin one up using Vercel.
Before you can create a database using Vercel, you first need to deploy your app to Vercel.


.env file. They should look something like this:Now that your database is created and connected to your app, it's time to create a database model. The main entity of the application is a Post that represents each entry in the blog app, so add the following Post model to your schema.prisma file:
Run the following command to apply your schema to your database:
This creates an initial migration creating the Post table and applies that migration to your database.
Now it's time to set up the Prisma Client and connect it to your database. You'll want to create a single client and bind it to the global object so that only one instance of the client is created in your application. This helps resolve issues with hot reloading that can occur when using Prisma with Next.js in development mode.
Create the lib/prisma.ts file and add the following code to it:
Now that all of the set up is complete, it's time to start building out your app!
Let's start with your homepage. Replace the contents of app/page.tsx with the following code:
This code fetches all posts from your database and displays them on the homepage, showing the title and author ID for each post. It uses the prisma.post.findMany() method, which is a Prisma Client method that retrieves all records from the database.
That shows how to query for all records, but how do you query for a single record?
Let's add a page that displays a single post. This page uses the URL parameters to get the post's ID, and then fetches it from your database and displays it on the page, showing the title, author ID, and content. It uses the prisma.post.findUnique() method, which is a Prisma Client method that retrieves a single record from the database.
Create the app/posts/[id]/page.tsx file and paste the following code in it:
Test the page by navigating to a post's URL. For example, http://localhost:3000/posts/1. For now, it should show a "No post found" message because you haven't created any posts yet. Let's add a way to create posts.
Next you'll create a page that allows users to create new posts. This page uses Clerk's auth() helper to get the user's ID. It is a helper that is specific to Next.js App Router, and it provides authentication information on the server side.
createPost() function is called. This function creates a new post in the database using the prisma.post.create() method, which is a Prisma Client method that creates a new record in the database.Create the app/posts/create/page.tsx file and paste in the following code:
Test the page by navigating to the /posts/create page (ex: http://localhost:3000/posts/create) and create a new post. You should be redirected to the homepage, where you should see the new post.
@tanstack/react-query, and zodNow, you've got a Next.js, Clerk, and Prisma app that can create and display posts. You could stop here and have a perfectly functional app. But let's take it a step further and add tRPC to your app for type-safe API endpoints.
Let's start by installing the following dependencies:
trpc is a wrapper around your API endpoints to make them type-safe and easier to use.zod is a schema validation library, also used to enhance your app's type safety.@tanstack/react-query is a library for data fetching and caching.Run the following command to install the packages:
At the time of writing,
clerk-next-appincludes React 19 as a peer dependency, but@tanstack/react-querydoes not. So, you'll need to use the--forceflag when running the command above. You may not need the--forceflag in the future.
Now, you'll configure tRPC for your app. You'll start by initializing a tRPC server that creates a router and publicProcedure that you can use to create your API endpoints.
Create the app/server/trpc.ts file and paste in the following code
Now, you'll create a router that's going to have your procedures on it. The following code creates a router with a getPosts procedure that uses the tRPC publicProcedure you created in the previous step to make a query using tRPC's query() method. The query then uses Prisma to query the Post model in your database. That part should look familiar, because you've used prisma.post.findMany() in your app earlier!
Create the app/server/routers/posts.ts file and paste in the code below:
This is the file where you'll add all of your queries and mutations, so you'll probably update this file frequently as you build out your app.
Now you need to connect the tRPC router to your App Router. You'll use a Route Handler that uses tRPC's fetchRequestHandler() method to pass requests from Next.js to the tRPC router.
Create the app/api/trpc/[trpc]/route.ts file and paste in the code below:
At this point, your API endpoint should be working. You can test it by navigating to http://localhost:3000/api/trpc/getPosts. You should see a JSON response with the posts from your database.
So far, your app is entirely server-side and static. You need a way to mutate data, which is where @tanstack/react-query comes in. But to use tRPC with @tanstack/react-query, you need to create a tRPC client.
Create the app/_trpc/client.ts file and paste in the code below:
To use Tanstack Query and tRPC together, you need to create a provider using the React Context API. This provider will make both the Tanstack Query client and the tRPC client available to your app using the trpc.Provider and QueryClientProvider components.
Create the app/_trpc/Provider.tsx file and paste in the code below:
Now, wrap your app in the provider. Update the main layout to import the provider as TRPCProvider and wrap your app in it. It's very important that <ClerkProvider> is wrapped around <TRPCProvider>, and not the other way around, because the <TRPCProvider> needs to have access to the Clerk authentication context.
In app/layout.tsx, add the following code:
Now, you can use the trpc client to fetch and mutate data in your app! Let's update the functionality of your app to use the trpc client.
Let's start by updating the homepage where the list of posts is rendered. Since the page is still rendered server-side, you'll create a client component that uses the trpc client to fetch posts.
Create the app/components/Posts.tsx file and paste in the following code:
Then, update the homepage to use the <Posts /> component:
Notice that the prisma.post.findMany() function is no longer used. Instead, your app is using trpc.getPosts.useQuery() in the <Posts /> component to fetch the posts, because remember, you created a tRPC postRouter with a getPosts procedure that uses prisma.post.findMany(). So now, you don't need to use Prisma directly, you can use tRPC in order to have type safety and a better developer experience. Let's update the rest of your app to use tRPC.
Of course, let's test and make sure the new logic is working. Navigate to the homepage and make sure you can see the posts.
Once you've verified everything's working, let's go back to your postRouter and create more procedures to handle your other queries.
In app/server/routers/posts.ts, update the code to match the following:
This adds a getPost procedure to fetch a single post by ID.
In app/posts/[id]/page.tsx, update the code to match the following:
This replaces prisma.post.findUnique() with trpc.getPost.useQuery(). Because tRPC is using Tanstack Query to fetch the data, the query result includes the data and other states, such as loading and error. You can learn more about in the Tanstack Query docs.
And before you go any further, test to make sure the new logic is working. Navigate to a post's URL, such as http://localhost:3000/posts/1, and make sure you can see the post.
If that's working, let's go back to your postRouter and add the last procedure you need to handle your create post functionality.
In app/server/routers/posts.ts, add the following code:
This adds a createPosts procedure that creates a new post.
In app/posts/create/page.tsx, replace the existing code with the following:
This updates a few things. First, it turns this page into a client component, because Tanstack Query and the tRPC client are client-side. So now, the Server Action that you created before can no longer be used. Instead, the form data is handled using state. When the form is submitted, the createPost() function no longer uses prisma.post.create(), but instead uses trpc.createPosts.useMutation() from the tRPC client. Also, because the page is now a client component, Clerk's auth() helper no longer works, so it's replaced with Clerk's useAuth() hook. This introduces the benefit of having access to Clerk's loading state, so a loading UI is added.
And don't forget, test your changes. Navigate to the create post page, such as http://localhost:3000/posts/create, and make sure you can create a new post.
Once you've confirmed everything's working, you're almost done...
In many applications, it's essential to restrict access to certain routes based on user authentication status. This ensures that sensitive data and functionality are only accessible to authorized users.
The benefit of using Clerk with tRPC is that you can create protected procedures using Clerk's authentication context. Clerk's Auth object includes important authentication information like the current user's session ID, user ID, and organization ID. It also contains methods to check for the current user's permissions and to retrieve their session token. You can use the Auth object to access the user's authentication information in your tRPC queries.
In your server directory, create a context.ts file with the following code:
This creates a context that will be used to create the context for every tRPC query sent to the server. The context will use the auth() helper from Clerk to access the user's Auth object.
Then, in your tRPC server (app/api/trpc/[trpc]/route.ts), pass the context:
The tRPC context, or ctx, should now have access to the Clerk Auth object.
In your server/trpc.ts file, create a protected procedure:
Once you have created your procedure, you can use it in any router. In this case, you don't want unauthenticated users to be able to create posts, so let's update the createPosts mutation to be protected by swapping the publicProcedure with the protectedProcedure:
At this point, you've got a fully functional app for creating and displaying posts. You can now add more features to your app, such as updating and deleting posts, adding comments, storing more author information from the Clerk User object, and more.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。