Great question! With Next.js (especially in the App Router, i.e., /app directory), the way you define API routes has changed compared to the old /pages/api convention. When using tRPC with Next.js, you typically do not use the /api/abc/route.ts file structure for your API endpoints. Instead, your tRPC router is set up in a custom server file (often under /server or /trpc), and you expose a single API handler (e.g., /api/trpc).
Key Points:
1. Old Way (/pages/api/abc.ts):
- You could call
fetch('/api/abc') and it would hit that API route.
2. App Router (/app/api/abc/route.ts):
- You could call
fetch('/api/abc') and it would hit that API route.
3. tRPC with Next.js (Common Setup):
- You do not create individual API route files for each endpoint.
- Instead, you set up a single tRPC handler (e.g.,
/api/trpc/[trpc]).
- All tRPC requests go through this handler, and you use the tRPC client to call your procedures.
So, will fetch('/api/abc') work?
No, not by default if you are using tRPC and your files are in /server/ (not in /api/abc/route.ts).
- There is no
/api/abc endpoint unless you explicitly create it.
- tRPC expects you to use its client to call procedures, not to fetch individual REST endpoints.
How to Call tRPC Endpoints
- From the client: Use the tRPC client hooks (e.g.,
trpc.abc.useQuery()).
- From the server: Use the tRPC server helpers.
If you want to call a tRPC procedure from the client, you do not use fetch('/api/abc').
Instead, you use the tRPC client, which will make a request to your tRPC handler (e.g., /api/trpc).
If you want to keep using fetch('/api/abc'):
- You must create an API route at
/api/abc (e.g., /app/api/abc/route.ts or /pages/api/abc.ts).
- This is separate from tRPC.
Summary Table
| Setup | Can you use fetch('/api/abc')? | How to call? |
|---|
/pages/api/abc.ts | ✅ | fetch('/api/abc') |
/app/api/abc/route.ts | ✅ | fetch('/api/abc') |
tRPC in /server/ | ❌ | Use tRPC client |
| tRPC with custom API handler | ❌ (unless you make one) | Use tRPC client |
What should you do?
- If you want REST endpoints: Use
/app/api/abc/route.ts or /pages/api/abc.ts.
- If you want tRPC: Use the tRPC client, and do not use
fetch('/api/abc').
Example tRPC Setup in Next.js
// /pages/api/trpc/[trpc].ts (for pages router)
// or /app/api/trpc/[trpc]/route.ts (for app router)
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { appRouter } from '../../../server/trpc/router';
export default createNextApiHandler({
router: appRouter,
createContext: () => ({}),
});
Client usage:
const { data } = trpc.abc.useQuery();
If you need more details or want to mix tRPC and REST, let me know!