Search code examples
reactjsjsonhttp-headersnext.js13

How to handle the NextResponse in NextJS 13.4


How can I receive the content of my request? Let's say we have a brand new app in NextJS 13.4 and in the app/api/route.tsx we have this

import { NextResponse } from 'next/server'
 
export async function GET() {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
    headers: {
      'Content-Type': 'application/json',
    },
  })
  const data = await res.json()
 
  return NextResponse.json({ data })

}

I want to know two things: why to use NextResponse and how.

The documentation don't show us how to handle the values in the page.js/ts

so here in the app/page.tsx I have this

import Image from 'next/image'
import { GET } from '../api/route'

export default async function Home() {
    const data  = await GET()
    console.log(data)
    return(
        <>
            <div>Contents</div>
            <div>Goes Here</div>
        </>
    )
}

What is the right way to handle this? Because this is returning a bunch of header things and I couldn't find the content. If I remove this NextResponse.json({ data }) and return only the data I'm able to get the values like this

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

So can anyone explain me why the documentation tell me to use the NextResponse but don't explain how can I get the value in the actual front end.

It is right the way I'm importing and trying to receive the value?


Solution

  • pages/api/route.ts

    • Request is the standard Web API that you use in the browser and in recent versions of Node.js

    • NextRequest is a subclass of Request that adds several properties and methods. It's used in middleware

    • NextApiRequest extends Node.js' IncomingMessage (from node:http) and also adds several helpers to it. It's used in API routes

         import { NextResponse } from 'next/server'
         import type { NextApiRequest, NextApiResponse } from 'next';
      
        export async function handle(req: NextApiRequest, resp: NextApiResponse) {
         if (req.method === 'GET') {
             const res = await fetch('http://jsonplaceholder.typicode.com/todos/1', {
                 headers: {
                     'Content-Type': 'application/json',
                 },
             })
             const data = await res.json()
      
             return resp.status(201).json(data);
         }
       }
      export default handle
      

    pages/app/index.tsx

    import {useEffect, useState} from 'react'
    const Page = (props) => {
    const [state,setState]= useState([])
    const getData = async () => {
    const res = await fetch(`/api/route`
      , {
        method: "GET",
      },
    )
    const pos = await res.json()
     setState(pos)
    
    }
    useEffect(() => {
    getData()
    }, [])
    
    console.log(state);
    
     return (
       <>
        <div >
       {state.map((item) => (
     <>
    <p>{item.id}</p>
    <p>{item.title}</p>
    </>))}
     </div>
     </>
    )}
    export default Page