0
0
NextjsHow-ToBeginner · 3 min read

How to Create a GET API in Next.js: Simple Guide

In Next.js, create a GET API by adding a GET function inside a file under the app/api folder. This function returns a Response object with the data you want to send back. The file path defines the API endpoint URL.
📐

Syntax

To create a GET API in Next.js, export an async GET function from a file inside the app/api directory. This function receives a Request object and returns a Response object.

  • GET: The exported function name that handles GET requests.
  • request: The incoming HTTP request object.
  • Response: The object you return with status and body.
  • app/api/your-path/route.js: The file path defines the API endpoint URL.
javascript
export async function GET(request) {
  return new Response('Hello from GET API')
}
💻

Example

This example shows a simple GET API that returns JSON data with a message. The API is available at /api/hello.

javascript
export async function GET(request) {
  const data = { message: 'Hello from Next.js GET API' };
  return new Response(JSON.stringify(data), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
}
Output
{"message":"Hello from Next.js GET API"}
⚠️

Common Pitfalls

Common mistakes when creating GET APIs in Next.js include:

  • Not exporting the GET function, so the API route does not respond.
  • Returning plain objects instead of a Response object.
  • Forgetting to set the Content-Type header when returning JSON.
  • Placing the API file outside the app/api folder, so Next.js does not recognize it as an API route.
javascript
/* Wrong way: returning object directly */
export async function GET(request) {
  return { message: 'This will not work' };
}

/* Right way: return Response with JSON string and headers */
export async function GET(request) {
  return new Response(JSON.stringify({ message: 'This works' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
}
📊

Quick Reference

ConceptDescription
File locationPlace API files under app/api/your-endpoint/route.js
Function nameExport async function named GET for GET requests
Return typeReturn a Response object with status and body
Response bodyUse JSON.stringify for JSON data
HeadersSet 'Content-Type' to 'application/json' for JSON responses

Key Takeaways

Create GET APIs in Next.js by exporting an async GET function inside app/api folder.
Always return a Response object with proper status and headers, not plain objects.
Set 'Content-Type' header to 'application/json' when returning JSON data.
The file path inside app/api defines the API endpoint URL.
Avoid placing API files outside app/api or forgetting to export the GET function.