I'm fairly new to React JS and Next.js. I was previously using the Page Router API in Next.js but then switched to use the new App Router in Next.js 13.
Previously, using the Page Router, the structure to create a single GET request was to nest your "JS" file under the page\api
. The server automatically creates the route and returns the methods + data. For example, I would export the following function:
export default (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
Now, using the App Router and TS on Next.js 13, I understand that the mechanism is different. The API folder is nested under the app folder and you have to define a "route.ts" file with all the different GET, POST (etc..) methods:
import { NextApiRequest } from 'next';
import React from 'react';
export async function GET (request:NextApiRequest){
return new Response('John Doe')
}
I have some problems understanding how to use this Response
object. How to you specify the structure of what you return, in my case { name: 'John Doe' }
? I want to change the response status to 400, how do I do that?
Going forward, I have to deal with a POST request.
import type {NextApiRequest, NextApiResponse} from 'next'
type MyData ={
name:string
}
export async function POST(
req: NextApiRequest,
res: NextApiResponse<Data>
){
const {nameLookup} = req.body
if(!nameLookup){
//WHAT I WOULD LIKE TO DO IF I WAS USING THE PAGE ROUTER
//BUT THIS IS NOT WORKING WITH THE APP ROUTER
res.statusCode = 400
//- error TypeError: res.json is not a function
res.json({name:'Please provide something to search for'})
return res
}
//WHAT I WOULD LIKE TO DO IF I WAS USING THE PAGE ROUTER
//BUT THIS IS NOT WORKING WITH THE APP ROUTER
//- error TypeError: res.status is not a function
return res.status(200).json({anwser:'John Doe'})
})
Thanks for helping, the learning curve is a bit steep having to deal with everything at the same time (TS, Next.js 13)
Here is a example based on your route:
export async function POST(request: NextRequest) {
const { nameLookup }: MyData = await request.json();
if (!nameLookup) {
return new NextResponse(
JSON.stringify({ name: "Please provide something to search for" }),
{ status: 400 }
);
}
return new NextResponse(JSON.stringify({ answer: "John Doe" }), {
status: 200,
});
}
See the app router documentation for more details.