102
LVL 04 — SENIOR-IN-TRAININGSESSION 102DAY 102

NEXT.JS API ROUTES

🎫 PIXELCRAFT-088
Feature | 🔴 Expert | Priority: 🟡 Medium

Explore moving some API endpoints to Next.js API routes. Compare with standalone Express. Understand when to use each approach. Build the hybrid architecture — Next.js for public pages, Express for the core API.
CONCEPTS.UNLOCKED
🛤️
Next.js API Routes
Backend endpoints inside the Next.js app. app/api/images/route.ts → handles GET /api/images. No separate Express server needed for simple endpoints. Colocated with your frontend code.
📡
Route Handlers
Export async GET, POST, PUT, DELETE functions. Each function handles one HTTP method. Access request body, headers, cookies. Return NextResponse.json(). Clean, explicit, typed.
Server Actions
Call server functions directly from React components. Mark a function with 'use server' → call it from a form or onClick. No API endpoint needed. Next.js generates the RPC layer automatically.
🔀
When Next.js vs Express
Next.js API: simple CRUD, tightly coupled with frontend. Express: complex APIs, WebSockets, background jobs, microservices. Most projects use a hybrid: Next.js for pages + Express for the heavy backend.
🛡️
Next.js Middleware
middleware.ts runs before every request. Auth checks, redirects, headers, rate limiting — at the edge, before the page even renders. One file, protects all routes.
HANDS-ON.TASKS
01
Create API Route Handlers
// app/api/images/route.ts import { NextResponse } from 'next/server'; import { connectDB } from '@/lib/db'; export async function GET() { const db = await connectDB(); const images = await db .collection('images') .find({ public: true }) .limit(50) .toArray(); return NextResponse.json(images); } export async function POST( request: Request ) { const body = await request.json(); // Validate, save, return const db = await connectDB(); const result = await db .collection('images') .insertOne(body); return NextResponse.json( { id: result.insertedId }, { status: 201 } ); }
02
Auth Middleware
// middleware.ts import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export function middleware( request: NextRequest ) { // Protect /editor routes if (request.nextUrl.pathname .startsWith('/editor')) { const token = request.cookies.get('token'); if (!token) { return NextResponse.redirect( new URL('/login', request.url)); } } return NextResponse.next(); } export const config = { matcher: ['/editor/:path*'], };
Middleware runs at the edge — before the page even starts rendering. Unauthenticated users are redirected to /login instantly. No flash of protected content.
03
Server Actions
// app/actions/favorites.ts 'use server'; import { getAuthUser } from '@/lib/auth'; import { connectDB } from '@/lib/db'; import { revalidatePath } from 'next/cache'; export async function toggleFavorite( imageId: string ) { const user = await getAuthUser(); const db = await connectDB(); await db.collection('favorites') .updateOne( { userId: user._id, imageId }, { $set: { favorited: true } }, { upsert: true } ); revalidatePath('/gallery'); } // In a component — no fetch needed: // <button onClick={ // () => toggleFavorite(image.id) // }> // ♥ Favorite // </button>
Server Actions eliminate the API endpoint entirely. The function runs on the server, called directly from the client. Next.js handles serialization, error handling, and revalidation.
04
Compare Architectures
// Architecture comparison: Standalone Express: ✅ Complex APIs, WebSockets ✅ Background jobs (BullMQ) ✅ Independent scaling ✅ Team separation ❌ Separate deployment Next.js API routes: ✅ Simple CRUD ✅ Colocated with frontend ✅ Single deployment ✅ Server Actions (no API needed) ❌ No WebSockets, no long-running Hybrid (PixelCraft's choice): Next.js → public pages, gallery, landing, simple API Express → core API, WebSockets, background workers, heavy logic // The answer is almost always hybrid.
05
Close the Ticket
git switch -c feature/PIXELCRAFT-088-nextjs-api git add pixelcraft-web/ git commit -m "Add Next.js API routes + middleware + Server Actions (PIXELCRAFT-088)" git push origin feature/PIXELCRAFT-088-nextjs-api # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Monolith vs microservices vs "modular monolith."

The industry trend in 2025 is toward colocated full-stack apps for most projects, with separate services only when scale or team structure demands it.

// Architecture evolution:

Monolith (everything in one app)
  Simple, fast, works for most
  Breaks at scale + large teams

SPA + API (separate front/back)
  React SPA + Express API
  Two deploys, CORS headaches
  PixelCraft started here

Full-stack framework
  Next.js, Remix, SvelteKit
  Single deploy, colocated code
  Server + client in one project

Microservices
  Independent services, teams, deploys
  Complex, expensive, powerful
  Only when you outgrow the above

// Understanding WHEN to split is
// the senior engineering judgment.
"Full-Stack Lab"
[A]Add a Server Action for image deletion: 'use server' function that validates ownership, deletes from S3 and MongoDB, then revalidates the gallery. Test: delete → gallery updates instantly without a page refresh.
[B]Add rate limiting to middleware: use the edge runtime to check Redis for request counts per IP. Block excessive requests before they reach your API. Compare to Express-level rate limiting.
[C]Research: compare Next.js vs Remix vs Astro vs SvelteKit. When would you choose each? What are their rendering strategies, data loading patterns, and deployment targets? Write a comparison document.
REF.MATERIAL
ARTICLE
Vercel
Official guide: creating API endpoints with route handlers. GET, POST, PUT, DELETE, streaming, and Edge Runtime.
NEXTJSOFFICIALESSENTIAL
ARTICLE
Vercel
Official Server Actions guide: 'use server', form actions, revalidation, error handling. The new way to mutate data in Next.js.
ACTIONSOFFICIAL
VIDEO
Lee Robinson (Vercel)
Practical Server Actions tutorial from Vercel's VP of Product: forms, mutations, optimistic updates, and error handling.
ACTIONSTUTORIAL
ARTICLE
Vercel
Official middleware guide: auth checks, redirects, headers, and request rewriting. Runs at the edge before your page renders.
MIDDLEWAREOFFICIAL
VIDEO
Fireship
When to use monolith, microservices, or serverless. The tradeoffs that matter: team size, scale, deployment complexity.
ARCHITECTUREQUICK
// LEAVE EXCITED BECAUSE
You understand the full spectrum: SPA + API, server-rendered, static, and hybrid. Server Actions eliminate entire API endpoints. Middleware protects routes at the edge. You can choose the right architecture for any project.