#How do I handle both GET and POST requests (Non-API) like how PHP handles both?
1 messages · Page 1 of 1 (latest)
Hi @cinder breach. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
How do I handle both GET and POST requests (Non-API) like how PHP handles both?
In Next.js, you can handle both GET and POST requests using Route Handlers. Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.
Here's a basic example of how you can handle GET and POST requests:
export async function GET(request: Request) {
// Handle GET request
}
export async function POST(request: Request) {
// Handle POST request
}
In the above code, GET and POST are async functions that handle GET and POST requests respectively. The request object is a NextRequest object, which is an extension of the Web Request API. NextRequest gives you further control over the incoming request, including easily accessing cookies and an extended, parsed, URL object nextUrl [source] (https://nextjs.org/docs/app/api-reference/file-conventions/route).
If you want to pass the POST body to the React components, you can use the request object to access the body of the POST request. Here's an example:
export async function POST(request: Request) {
const { logo, title, standard, twitter, discord, telegram, userId } = await request.json();
// Pass the data to the React components
}
In the above code, request.json() is used to parse the body of the POST request as JSON [source] (https://github.com/vercel/next.js/issues/50491).
Please note that Route Handlers are only available inside the app directory. You do not need to use API Routes (pages) and Route Handlers (app) together, as Route Handlers should be able to handle all use cases [source] (https://nextjs.org/docs/app/api-reference/file-conventions/route).
If you previously used API routes to call an external API from the client, you can now use Server Components instead to securely fetch data [source] (https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#api-routes).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@cinder breach kapa.ai is still learning and improving, please let us know how it did by reacting below