Creating an API Route
- Location: API routes reside in a dedicated folder named pages/api. Any file placed inside this folder is treated as an API endpoint.
- File Naming: The file name determines the URL path for accessing the API route. For example, a file named hello.js at pages/api/hello.js would be accessible at /api/hello.
- Function Structure: Each API route file should export a default function that takes two arguments:
- req: This is an instance of http.IncomingMessage object containing information about the incoming HTTP request (headers, body, etc.).
- res: This is an instance of http.ServerResponse object used to send the response back to the client (including status code, headers, and response data).
// api/routs.js
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({
hello:"Geeks For Geeks",
})
}
In this example, visiting `/api/users/123` in your Next.js application will trigger this API route, and it will respond with a JSON object containing the user data for ID 123.
How to use Next.js API Routes?
Next.js API Routes are a feature of Next.js that allows you to create server-side logic and APIs within your Next.js application. These API routes are implemented using files in the `pages/api` directory of your Next.js project. When you deploy your Next.js application, these API routes are automatically served as serverless functions.
Table of Content
- Key points about Next.js API Routes
- Dynamic API Routes
- Creating an API Route
- API Routes custom configuration
- Typing API Routes with TypeScript
- Accessing an API Route
- Conclusion