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
GETfunction, so the API route does not respond. - Returning plain objects instead of a
Responseobject. - Forgetting to set the
Content-Typeheader when returning JSON. - Placing the API file outside the
app/apifolder, 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
| Concept | Description |
|---|---|
| File location | Place API files under app/api/your-endpoint/route.js |
| Function name | Export async function named GET for GET requests |
| Return type | Return a Response object with status and body |
| Response body | Use JSON.stringify for JSON data |
| Headers | Set '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.