Next.js Discord

Discord Forum

nest JS with Next js

Answered
American Sable posted this in #help-forum
Open in Discord
American SableOP
Hi, I'm working with nest js for the first time, and have fixed so I can get the url to next js frontend.

In my app/api/apartments i have a route.ts

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    const fetchData = await fetch('http://localhost:4000/api/apartments')
    const data = await fetchData.json()

    res.status(200).json({ data })
  } else {
    // Handle any other HTTP method
  }
}


Then i trying to get that route in my page.tsx but it doenst work
async function getData() {
  const res = await fetch("/api/apartments");
  const data = await res.json();
  return data;
}
Answered by Ray
the route handler should look like this
// app/api/apartments
export async function GET(req: Request) {
    try {
      const fetchData = await fetch('http://localhost:4000/api/apartments')
      const data = await fetchData.json()
  
      return Response.json(data)
    } catch (e) {
      console.log(e)
      return Response.json({ error: "something went wrong" }
    }
}

and if you are fetching on server side, you will need to provide the absolute path to the getData() function.
btw, you should avoid fetching route handler in server component
https://nextjs-faq.com/fetch-api-in-rsc
View full answer

1 Reply

@American Sable Hi, I'm working with nest js for the first time, and have fixed so I can get the url to next js frontend. In my app/api/apartments i have a route.ts ts export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'GET') { const fetchData = await fetch('http://localhost:4000/api/apartments') const data = await fetchData.json() res.status(200).json({ data }) } else { // Handle any other HTTP method } } Then i trying to get that route in my page.tsx but it doenst work ts async function getData() { const res = await fetch("/api/apartments"); const data = await res.json(); return data; }
the route handler should look like this
// app/api/apartments
export async function GET(req: Request) {
    try {
      const fetchData = await fetch('http://localhost:4000/api/apartments')
      const data = await fetchData.json()
  
      return Response.json(data)
    } catch (e) {
      console.log(e)
      return Response.json({ error: "something went wrong" }
    }
}

and if you are fetching on server side, you will need to provide the absolute path to the getData() function.
btw, you should avoid fetching route handler in server component
https://nextjs-faq.com/fetch-api-in-rsc
Answer