





























This guide will cover how you can build APIs with Next.js, including setting up your project, understanding the App Router and Route Handlers, handling multiple HTTP methods, implementing dynamic routing, creating reusable middleware logic, and deciding when to spin up a dedicated API layer.
If you’re starting fresh, you can create a new Next.js project using:
Note: The
--apiflag automatically includes an exampleroute.tsin your new project’sapp/folder, demonstrating how to create an API endpoint.
pages/api/* for APIs. This approach relied on Node.js request/response objects and an Express-like API.pages/api/*, you can now place route.ts or route.js files anywhere inside the app/ directory.Why switch? The App Router’s “Route Handlers” lean on the Web Platform Request/Response APIs rather than Node.js-specific APIs. This simplifies learning, reduces friction, and helps you reuse your knowledge across different tools.
Public API for Multiple Clients
Proxy to an Existing Backend
Webhooks and Integrations
Custom Authentication
Note: If you only need server-side data fetching for your own Next.js app (and you don’t need to share that data externally), Server Components might be sufficient to fetch data directly during render—no separate API layer is required.
In the App Router (app/), create a folder that represents your route, and inside it, a route.ts file.
For example, to create an endpoint at /api/users:
Unlike the Pages Router API routes (which had a single default export), you can export multiple functions representing different HTTP methods from the same file.
Now, sending a GET request to /api/users returns your list of users, while a POST request to the same URL will insert a new one.
By default, your Route Handler methods (GET, POST, etc.) receive a standard Request object, and you must return a standard Response object.
The cookies() and headers() functions can be helpful if you plan to re-use shared logic across other server-side code in Next.js. You'll notice Next.js also provides NextRequest and NextResponse which extend the base Web APIs.
To create dynamic paths (e.g. /api/users/:id), use Dynamic Segments in your folder structure:
This file corresponds to a URL like /api/users/123, with the 123 captured as a parameter.
Here, params.id gives you the dynamic segment.
A common scenario is proxying an existing backend service. You can authenticate requests, handle logging, or transform data before sending it to a remote server or backend:
Now your clients only need to call /api/external, and Next.js will handle the rest. This is also sometimes called a “Backend for Frontend” or BFF.
If you want to apply the same logic (e.g. authentication checks, logging) across multiple Route Handlers, you can create reusable functions that wrap your handlers:
Then in your Route Handler:
The standard Next.js server deployment using next start enables you to use features like Route Handlers, Server Components, Middleware and more – while taking advantage of dynamic, request time information.
There is no additional configuration required. See Deploying for more details.
Next.js also supports outputting your entire site as a static Single-Page Application (SPA).
You can enable this by setting:
In static export mode, Next.js will generate purely static HTML, CSS, and JS. You cannot run server-side code (like API endpoints). If you still need an API, you’d have to host it separately (e.g., a standalone Node.js server).
Note:
- GET Route Handlers can be statically exported if they don’t rely on dynamic request data. They become static files in your out folder.
- All other server features (dynamic requests, rewriting cookies, etc.) are not supported in a pure SPA export.
If you are deploying your Next.js application to Vercel, we have a guide on deploying APIs. This includes other Vercel features like programmatic rate-limiting through the Vercel Firewall. Vercel also offers Cron Jobs, which are commonly needed with API approaches.
With the App Router’s React Server Components, you can fetch data directly on the server without exposing a public endpoint:
If your data is only used inside your Next.js app, you may not need a public API at all.
npx create-next-app@latest --api.app/ directory (e.g., app/api/users/route.ts).GET, POST, PUT, DELETE, etc.) in the same file.Request object and return a Response.fetch('/api/...')).withAuth()) for auth or other repeated logic.Using the Next.js App Router and Route Handlers gives you a flexible, modern way to build APIs that embrace the Web Platform directly. You can:
[id] segment folder structure.You can think of Server Actions like automatically generated POST API routes that can be called from the client.
They are designed for mutation operations, such as creating, updating, or deleting data. You call a Server Action like a normal JavaScript function, versus making an explicit fetch to a defined API route.
While there is still a network request happening, you don't need to manage it explicitly. The URL path is auto-generated and encrypted, so you can't manually access a route like /api/users in the browser.
If you plan to use Server Actions and expose a public API, we recommend moving the core logic to a Data Access Layer and calling the same logic from both the Server Action and the API route.
Yes, you can use TypeScript with Route Handlers. For example, defining the Request and Response types in your route file.
Learn more about TypeScript with Next.js.
Learn more in our authentication documentation.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。