0Pricing
Frontend Academy · Lesson

Next.js API Routes and Middleware

Create serverless API endpoints in the api/ directory, process requests in Route Handlers, and run edge Middleware for auth and redirects.

Why API Routes?

Next.js bundles a server with your app — you can write backend endpoints alongside your pages without a separate Node project. Great for proxying, form submissions, webhooks, and small APIs.

Pages Router API Routes

Files in pages/api/ export a default function with Express-style (req, res).

// pages/api/users.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    const users = await db.users.findMany();
    return res.json(users);
  }
  if (req.method === 'POST') {
    const user = await db.users.create({ data: req.body });
    return res.status(201).json(user);
  }
  return res.status(405).end();
}

All lessons in this course

  1. Pages Router vs App Router
  2. Server Components and Client Components
  3. SSG SSR and ISR
  4. Next.js API Routes and Middleware
← Back to Frontend Academy