Back to results for “Handlers”
Next.js › API Routes

What are API routes in Next.js and why would you use them?

Beginner

Answer

API routes let you build backend endpoints directly inside your Next.js project, so you can handle things like form submissions or database calls without setting up a separate server. This keeps your frontend and backend code together in one project, which is convenient for small to medium sized applications.
// pages/api/hello.js (Pages Router)
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from the API' });
}
Real-world example A small business website uses an API route to receive contact form submissions and send them by email, avoiding the need to run a separate backend server just for this one feature.

Common follow-ups: How are API routes different from Route Handlers in the App Router?;Can API routes connect directly to a database?