1.9K Views

NEXT111 - API Routes in Next.js

Learn how to build backend endpoints using Next.js API Routes, handle HTTP methods, return JSON responses, and connect frontend and backend logic in a single project.

Next.js allows you to build backend functionality directly inside your application using API Routes.
In this lesson, you will learn how API Routes work in the App Router and how to create simple backend endpoints without setting up a separate server.

What Are API Routes?

API Routes are server-side functions that handle HTTP requests and return responses, usually in JSON format.

They are commonly used for:

  • Fetching data
  • Handling form submissions
  • Authentication logic
  • Server-side validation
  • Acting as a backend for frontend components

API Routes make Next.js a fullstack framework.


API Routes in the App Router

In the App Router, API Routes are defined using route.js files.

File location pattern:

app/api/route.js

Each route.js file represents an API endpoint.


Creating a Basic API Route

Example folder structure:

app/api/hello/route.js

Basic GET handler:

export async function GET() {
  return new Response(
    JSON.stringify({ message: "Hello from API" }),
    {
      headers: { "Content-Type": "application/json" }
    }
  );
}

This endpoint is available at:

  • /api/hello

Handling HTTP Methods

API Routes can handle different HTTP methods.

Example:

export async function POST(request) {
  const body = await request.json();
 
  return new Response(
    JSON.stringify({ received: body }),
    { status: 201 }
  );
}

Supported methods include:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

Returning JSON Responses

Responses should be returned using the Response object.

return new Response(
  JSON.stringify({ success: true }),
  {
    status: 200,
    headers: { "Content-Type": "application/json"  }
  }
);

Always set appropriate status codes and headers.


Accessing Query Parameters

Query parameters can be accessed via the request URL.

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get("name");
 
  return new Response(
    JSON.stringify({ name }),
    { status: 200 }
  );
}

Example request:

  • /api/hello?name=Emre

Dynamic API Routes

Dynamic segments work the same as page routing.

Example structure:

app/api/posts/[id]/route.js

Accessing params:

export async function GET(request, { params }) {
  return new Response(
    JSON.stringify({ id: params.id }),
    { status: 200 }
  );
}

This allows building REST-like APIs.


Calling API Routes from the Frontend

API Routes can be called using fetch.

fetch("/api/hello")
  .then(res => res.json())
  .then(data => console.log(data));

This keeps frontend and backend tightly integrated.


API Routes and Security

Important security considerations:

  • Validate incoming data
  • Never expose secrets
  • Use server-side checks
  • Protect sensitive endpoints

API Routes run only on the server.


Common API Route Mistakes

Avoid these mistakes:

  • Writing heavy business logic without structure
  • Returning plain objects instead of Response
  • Forgetting HTTP status codes
  • Exposing private environment variables

Treat API Routes like a real backend.


Summary

In this lesson, you learned:

  • What API Routes are
  • How to create API endpoints
  • Handling HTTP methods
  • Returning JSON responses
  • Using query parameters
  • Dynamic API routes
  • Calling APIs from the frontend
  • Security best practices

In the next and final lesson, we will build a small Next.js project that combines routing, data fetching, SEO, styling, and API routes into a single application.