Introduction
In today’s web development landscape, creating robust APIs is a fundamental requirement for building modern applications. Next.js, a popular React framework for server-side rendering and static site generation, combined with Trpc, a versatile and efficient library for building APIs, offers a powerful solution for handling CRUD operations. In this article, we will explore how to leverage the combined strengths of Next.js and tRPC to create a simple CRUD API effortlessly.
Related Articles
1. Setting Up Next.js and tRPC
To begin, make sure you have Node.js and npm installed on your machine. Start by creating a new Next.js project by running the following commands in your terminal
npx create-next-app my-crud-app
cd my-crud-app
Next, install tRPC by running:
npm install trpc
2. Defining Your API Schema
With Next.js and tRPC set up, let’s define the schema for our CRUD API. Create a new folder called api in the root of your Next.js project. Inside the api folder, create a file named index.ts. This file will serve as the entry point for our API. Define your API schema using tRPC's declarative syntax. For example:
// api/index.ts
import { createTRPCClient } from '@trpc/client';
import type { AppRouter } from '../../pages/api/trpc/[trpc]';
import { httpBatchLink } from '@trpc/client/links/httpBatchLink';
export const trpc = createTRPCClient({
url: '/api/trpc',
links: [
httpBatchLink({ url: '/api/trpc/batch' }),
],
});
3. Creating the CRUD Endpoints
Inside the api folder, create a new file named trpc.ts. This file will contain the definitions for our CRUD endpoints. Define a router using tRPC's createRouter function. For example:
// api/trpc.ts
import { createRouter } from '@trpc/server';
import { z } from 'zod';
const router = createRouter()
.query('todos', {
resolve() {
return [
{ id: 1, title: 'Todo 1', completed: false },
{ id: 2, title: 'Todo 2', completed: true },
];
},
})
.mutation('createTodo', {
input: z.object({ title: z.string() }),
async resolve({ input }) {
// Logic to create a new todo
return { id: 3, title: input.title, completed: false };
},
})
.mutation('updateTodo', {
input: z.object({ id: z.number(), title: z.string(), completed: z.boolean() }),
async resolve({ input }) {
// Logic to update an existing todo
return input;
},
})
.mutation('deleteTodo', {
input: z.number(),
async resolve({ input }) {
// Logic to delete a todo
return input;
},
});
export type AppRouter = typeof router;
export default router;
4. Connecting the API with Next.js
Now, we need to connect our API with Next.js. Inside the pages/api folder, create a new folder called trpc. Inside the trpc folder, create two files: index.ts and batch.ts. In index.ts, import your API router and define the route handler:
// pages/api/trpc/index.ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { trpc } from '../../../api';
export default createNextApiHandler({
router: trpc,
});
In batch.ts, import your API router and define the batch route handler.
// pages/api/trpc/batch.ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { trpc } from '../../../api';
export default createNextApiHandler({
router: trpc,
batchEnabled: true,
});
5. Testing the CRUD API
Finally, we can test our CRUD API endpoints. Start the Next.js development server by running npm run dev. You can access the API endpoints at http://localhost:3000/api/trpc for individual requests and http://localhost:3000/api/trpc/batch for batched requests.
For example, to fetch all todos, you can send a GET request to http://localhost:3000/api/trpc/todos.
To create a new todo, you can send a POST request to http://localhost:3000/api/trpc/createTodo with the payload { "title": "New Todo" }.
Similarly, you can test the updateTodo and deleteTodo endpoints using the appropriate HTTP methods and payloads.
Conclusion
By combining the power of Next.js and tRPC, we have built a simple yet effective CRUD API effortlessly. Next.js provides the foundation for SSR and SSG, while tRPC enables us to define and handle our API endpoints with ease. This combination offers a robust solution for building scalable and efficient APIs in our Next.js applications. Happy coding!
Building a Simple CRUD API with Next.js and tRPC was originally published in Enlear Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.