Next.js: The React Framework (App Router)Entry 12 of 16
Route Handlers
A route.ts file exports functions named after HTTP methods (GET, POST, …) and turns a segment into an API endpoint using the Web Request and Response APIs.
nextjs.orgroute.js
Notes
- A folder can have
page.tsxorroute.ts, not both. - Use them for webhooks, endpoints called by third parties or mobile apps, and file or image responses.
- For your own UI's mutations, prefer Server Actions.
What / Why / When
- What
HTTP endpoints inside the Next.js app.
- Why
A small backend without a separate server.
- When
External callers, webhooks, non-HTML responses.
- Use case
A public JSON feed of posts.
Code compare
// app/api/posts/route.tsimport { NextRequest } from "next/server";export async function GET(request: NextRequest) { const limit = Number(request.nextUrl.searchParams.get("limit") ?? 10); const posts = (await getPosts()).slice(0, limit); return Response.json(posts);}export async function POST(request: Request) { const body = await request.json(); const post = await db.post.create({ data: body }); return Response.json(post, { status: 201 });}@angular/ssr generates an Express server.ts. Endpoints go there, before the Angular handler:
// server.ts (excerpt)const app = express();const angularApp = new AngularNodeAppEngine();app.use(express.json());app.get("/api/posts", async (req, res) => { const limit = Number(req.query["limit"] ?? 10); res.json((await loadPosts()).slice(0, limit));});// Angular SSR handles everything elseapp.use((req, res, next) => { angularApp .handle(req) .then((response) => (response ? writeResponseToNodeResponse(response, res) : next())) .catch(next);});Differences and gotchas
- For anything beyond a few endpoints, a real backend (your Go/Echo API) is cleaner in both stacks.
- Next.js route handlers use Web standard
Request/Response; Angular'sserver.tsuses Expressreq/res.
Quick reference
| Next.js | Angular |
|---|---|
app/api/posts/route.ts → GET | app.get('/api/posts', …) in server.ts |
Response.json() | res.json() |
NextRequest | Express req |