Route Handlers and API Routes in Next.js

Next.js is not only a client-side framework but a full-stack framework. You can build backend API endpoints by adding files to the api directory (and build client pages by adding files to the pages directory). For example, the route http://localhost:3000/api/example can be implemented by creating a file name example.js in the api directory:

// pages/api/example.js
export default function handler(req, res) {
    res.status(200).json({ message: 'Welcome to Sling Academy' })

If you access http://localhost:3000/api/example with a web browser, Postman, or any other HTTP client, you will see a JSON response like this:

The API Routes feature of Next.js helps you conveniently build both the backend and the front end in a single code base with zero setups. However, you can still use a different code base for the backend stuff if you use a programming language other than Javascript, such as Python or PHP.

Big update: Next.js 13 came to light with the new app directory and new feature: Route Handlers. They are equivalent to API Routes inside the pages directory. The decision to choose Route Handlers or API Routes is totally up to you.

This series of tutorials will teach you everything, from basic to advanced, about API Routes and Route Handlers in Next.js.

Notify of
Inline Feedbacks
View all comments